1use std::sync::atomic::{AtomicBool, Ordering};
43use std::sync::{Arc, Mutex, OnceLock, RwLock};
44use std::time::{Duration, Instant, SystemTime};
45
46use axum::body::Bytes;
47use axum::extract::Request;
48use axum::extract::{DefaultBodyLimit, Path, Query, RawQuery, State};
49use axum::http::header::{
50 ACCESS_CONTROL_ALLOW_HEADERS, ACCESS_CONTROL_ALLOW_METHODS, ACCESS_CONTROL_ALLOW_ORIGIN,
51 CONTENT_DISPOSITION, CONTENT_TYPE,
52};
53use axum::http::{HeaderMap, HeaderValue, StatusCode};
54use axum::middleware::{Next, from_fn, map_response};
55use axum::response::{IntoResponse, Response};
56use axum::routing::{get, post, put};
57use axum::{Json, Router};
58use heika_core::address::Address;
59use heika_core::hash::Hash256;
60use heika_core::key::PublicKey;
61use heika_core::network::NetworkIdentifier;
62use heika_core::patricia::{self, SubCache};
63use heika_rest::block::BlockInfo;
64use heika_rest::finalization::FinalizationProof;
65use heika_rest::merkle::{MerkleProofInfo, MerkleStateInfo};
66use heika_rest::node::{
67 AnnounceJson, AnnounceResultJson, ChainInfoJson, CommunicationTimestampsJson, CosignatureJson,
68 DelegationJson, DeploymentJson, ErrorJson, HealthStatusJson, NetworkJson,
69 NetworkPropertiesJson, NodeHealthJson, NodeInfoJson, NodeTimeJson, ServerInfoJson, ServerJson,
70 TransactionFeesJson, UnlockedAccountJson,
71};
72use heika_rest::send::TransactionStatus;
73use heika_rest::state::{
74 AccountInfo, AccountJson, AccountNamesJson, AccountRestrictionsInfo, AccountRestrictionsJson,
75 HashLockInfo, HashLockJson, MetadataEntryJson, MetadataInfo, MosaicInfo, MosaicNamesJson,
76 MosaicRestrictionEntryJson, MosaicRestrictionInfo, MosaicStateJson, MultisigGraphLevel,
77 MultisigInfo, MultisigJson, NamespaceInfo, NamespaceNameJson, SecretLockInfo, SecretLockJson,
78};
79use heika_rest::transaction::{TransactionInfo, parse_transaction_position};
80
81#[derive(Clone, Debug)]
83pub struct Snapshot {
84 pub node: NodeInfoJson,
85 pub peers: Vec<NodeInfoJson>,
87 pub chain: ChainInfoJson,
88 pub unlocked: UnlockedAccountJson,
89 pub delegations: Vec<DelegationJson>,
90}
91
92pub type Shared = Arc<RwLock<Snapshot>>;
94
95pub type Submit = Arc<dyn Fn(Vec<u8>) -> Result<(), String> + Send + Sync>;
98
99const HEIGHT_HEADER: &str = "x-heika-height";
101
102#[derive(Clone, Debug, PartialEq, Eq)]
104pub enum StateError {
105 Ahead { height: u64, tip: u64 },
107 NoHistory { height: u64 },
109 Invalid(String),
111 Other(String),
113}
114
115impl std::fmt::Display for StateError {
116 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
117 match self {
118 Self::Ahead { height, tip } => {
119 write!(f, "高さ {height} は、実行した高さ {tip} より上です")
120 }
121 Self::NoHistory { height } => write!(f, "高さ {height} の状態の差分を持っていません"),
122 Self::Invalid(message) => f.write_str(message),
123 Self::Other(message) => f.write_str(message),
124 }
125 }
126}
127
128impl From<String> for StateError {
129 fn from(message: String) -> Self {
130 Self::Other(message)
131 }
132}
133
134pub type KeyedStates = Vec<(Vec<u8>, Vec<u8>)>;
138
139pub trait Reader: Send + Sync {
141 fn accounts(
143 &self,
144 addresses: &[Address],
145 at: Option<u64>,
146 ) -> Result<Vec<AccountJson>, StateError>;
147 fn mosaics(&self, ids: &[u64], at: Option<u64>) -> Result<Vec<MosaicStateJson>, StateError>;
149 fn multisigs(
151 &self,
152 addresses: &[Address],
153 at: Option<u64>,
154 ) -> Result<Vec<MultisigJson>, StateError>;
155 fn lock_or_restriction_states(
160 &self,
161 cache: SubCache,
162 keys: &[Vec<u8>],
163 at: Option<u64>,
164 ) -> Result<KeyedStates, StateError>;
165 fn multisig_graph(
168 &self,
169 address: &Address,
170 at: Option<u64>,
171 ) -> Result<Option<Vec<MultisigGraphLevel>>, StateError>;
172 fn namespace(&self, id: u64, at: Option<u64>) -> Result<Option<NamespaceInfo>, StateError>;
175 fn metadata(
177 &self,
178 composite_hash: &Hash256,
179 at: Option<u64>,
180 ) -> Result<Option<MetadataEntryJson>, StateError>;
181 fn search_metadata(
185 &self,
186 filter: &MetadataFilter,
187 page: PageRequest,
188 after: Option<&MetadataPosition>,
189 at: Option<u64>,
190 ) -> Result<Option<Vec<MetadataEntryJson>>, StateError>;
191 fn search_namespaces(
195 &self,
196 filter: &NamespaceFilter,
197 page: PageRequest,
198 after: Option<&[u8]>,
199 at: Option<u64>,
200 ) -> Result<Option<Vec<(String, NamespaceInfo)>>, StateError>;
201 fn namespace_names(&self, ids: &[u64]) -> Result<Option<Vec<NamespaceNameJson>>, String>;
204 fn alias_names(&self, target: AliasTarget) -> Result<Option<Vec<String>>, String>;
206 fn state_path(
208 &self,
209 cache: SubCache,
210 key: &Hash256,
211 at: Option<u64>,
212 ) -> Result<MerkleStateInfo, StateError>;
213 fn block(&self, height: u64) -> Result<Option<BlockInfo>, String>;
215 fn finalization_proof(&self, epoch: u32) -> Result<Option<Vec<u8>>, String>;
217 fn transaction_status(&self, hash: &Hash256) -> Result<Option<TransactionStatus>, String>;
219 fn search_transactions(
223 &self,
224 filter: &TransactionFilter,
225 page: PageRequest,
226 after: Option<(u64, u32, u16)>,
227 ) -> Result<Option<Vec<TransactionInfo>>, String>;
228 fn confirmed_transaction(&self, hash: &Hash256) -> Result<Option<TransactionInfo>, String>;
230 fn transaction_merkle(
232 &self,
233 height: u64,
234 hash: &Hash256,
235 ) -> Result<Option<MerkleProofInfo>, String>;
236 fn transaction_fees(&self) -> Result<TransactionFeesJson, String>;
238 fn partial_transaction(&self, hash: &Hash256) -> Result<Option<TransactionInfo>, String>;
240 fn partial_transactions(&self, filter: &PartialFilter) -> Result<Vec<TransactionInfo>, String>;
242 fn unconfirmed_transaction(&self, hash: &Hash256) -> Result<Option<TransactionInfo>, String>;
244 fn unconfirmed_transactions(
247 &self,
248 filter: &PartialFilter,
249 embedded: bool,
250 ) -> Result<Vec<TransactionInfo>, String>;
251 fn network(&self) -> NetworkIdentifier;
253}
254
255#[derive(Clone, Debug, Default, PartialEq, Eq)]
257pub struct MetadataFilter {
258 pub source: Option<Address>,
259 pub target: Option<Address>,
260 pub scoped_key: Option<u64>,
261 pub target_id: Option<u64>,
262 pub metadata_type: Option<u8>,
263}
264
265#[derive(Clone, Debug, Default, PartialEq, Eq)]
267pub struct NamespaceFilter {
268 pub owner: Option<Address>,
269 pub level0: Option<u64>,
271 pub registration_type: Option<u8>,
273 pub alias_type: Option<u8>,
275}
276
277#[derive(Clone, Copy, Debug, PartialEq, Eq)]
279pub enum AliasTarget {
280 Address(Address),
281 Mosaic(u64),
282}
283
284#[derive(Debug, Default, serde::Deserialize)]
286#[serde(rename_all = "camelCase")]
287struct NamespaceQuery {
288 owner_address: Option<String>,
289 level0: Option<String>,
290 registration_type: Option<u8>,
291 alias_type: Option<u8>,
292 page_size: Option<usize>,
293 page_number: Option<usize>,
294 order: Option<String>,
295 offset: Option<String>,
296 height: Option<String>,
297}
298
299const MAX_NAME_IDS: usize = 100;
301
302const MAX_STATE_IDS: usize = 1000;
305
306#[derive(Clone, Copy, Debug, PartialEq, Eq)]
308pub struct MetadataPosition {
309 pub source: Address,
310 pub metadata_type: u8,
311 pub target: Address,
312 pub target_id: u64,
313 pub scoped_key: u64,
314}
315
316impl MetadataPosition {
317 fn parse(text: &str) -> Option<Self> {
319 if text.len() != 48 + 2 + 48 + 16 + 16 || !text.is_ascii() {
320 return None;
321 }
322 let address = |at: usize| Address::from_hex(&text[at..at + 48]).ok();
323 let id = |at: usize| hex_id(&text[at..at + 16]);
324 Some(Self {
325 source: address(0)?,
326 metadata_type: u8::from_str_radix(&text[48..50], 16).ok()?,
327 target: address(50)?,
328 target_id: id(98)?,
329 scoped_key: id(114)?,
330 })
331 }
332}
333
334#[derive(Clone, Copy, Debug, PartialEq, Eq)]
336pub struct PageRequest {
337 pub size: usize,
339 pub number: usize,
341 pub descending: bool,
342}
343
344#[derive(Clone, Debug, PartialEq, Eq)]
346pub struct TransactionFilter {
347 pub address: Option<Address>,
349 pub signer: Option<PublicKey>,
351 pub recipient: Option<[u8; 24]>,
353 pub types: Vec<u16>,
355 pub mosaic: Option<u64>,
357 pub from_amount: Option<u64>,
358 pub to_amount: Option<u64>,
359 pub from_height: u64,
361 pub to_height: u64,
362 pub embedded: bool,
365}
366
367#[derive(Debug, Default, serde::Deserialize)]
369#[serde(rename_all = "camelCase")]
370struct TransactionQuery {
371 address: Option<String>,
372 height: Option<String>,
373 from_height: Option<String>,
374 to_height: Option<String>,
375 page_size: Option<usize>,
376 page_number: Option<usize>,
377 order: Option<String>,
378 offset: Option<String>,
379 embedded: Option<String>,
380 signer_public_key: Option<String>,
381 recipient_address: Option<String>,
382 transfer_mosaic_id: Option<String>,
383 from_transfer_amount: Option<String>,
384 to_transfer_amount: Option<String>,
385}
386
387fn transaction_types(query: Option<&str>) -> Option<Vec<u16>> {
389 query
390 .unwrap_or_default()
391 .split('&')
392 .filter_map(|pair| pair.strip_prefix("type="))
393 .map(|value| value.parse::<u16>().ok())
394 .collect()
395}
396
397#[derive(Debug, Default, serde::Deserialize)]
399#[serde(rename_all = "camelCase")]
400struct MetadataQuery {
401 source_address: Option<String>,
402 target_address: Option<String>,
403 scoped_metadata_key: Option<String>,
404 target_id: Option<String>,
405 metadata_type: Option<u8>,
406 page_size: Option<usize>,
407 page_number: Option<usize>,
408 order: Option<String>,
409 offset: Option<String>,
410 height: Option<String>,
411}
412
413#[derive(Clone, Debug, Default, PartialEq, Eq)]
415pub struct PartialFilter {
416 pub address: Option<Address>,
418 pub signer: Option<PublicKey>,
420}
421
422#[derive(Debug, Default, serde::Deserialize)]
424#[serde(rename_all = "camelCase")]
425struct PartialQuery {
426 address: Option<String>,
427 signer_public_key: Option<String>,
428 page_size: Option<usize>,
429 page_number: Option<usize>,
430 embedded: Option<String>,
432}
433
434#[derive(serde::Serialize)]
436#[serde(rename_all = "camelCase")]
437struct Page<T> {
438 data: Vec<T>,
439 pagination: Pagination,
440}
441
442#[derive(serde::Serialize)]
443#[serde(rename_all = "camelCase")]
444struct Pagination {
445 page_number: usize,
446 page_size: usize,
447}
448
449#[derive(Clone)]
451pub struct Node {
452 pub submit: Submit,
453 pub submit_partial: Submit,
455 pub submit_cosignature: Submit,
457 pub submit_block: Submit,
459 pub reader: Arc<dyn Reader>,
460 pub network_properties: Arc<NetworkPropertiesJson>,
462 pub epoch: SystemTime,
464}
465
466static SOURCE: OnceLock<&'static [u8]> = OnceLock::new();
468
469pub fn offer_source(zip: &'static [u8]) {
472 let _ = SOURCE.set(zip);
473}
474
475pub fn offered_source() -> Option<&'static [u8]> {
477 SOURCE.get().copied().filter(|zip| !zip.is_empty())
478}
479
480#[derive(Clone)]
481struct Api {
482 shared: Shared,
483 node: Node,
484}
485
486const STOP_POLL: Duration = Duration::from_millis(200);
488
489fn read(api: &Api) -> Snapshot {
490 api.shared
492 .read()
493 .unwrap_or_else(|poisoned| poisoned.into_inner())
494 .clone()
495}
496
497async fn node_info(State(api): State<Api>) -> Json<NodeInfoJson> {
498 Json(read(&api).node)
499}
500
501async fn node_peers(State(api): State<Api>) -> Json<Vec<NodeInfoJson>> {
502 Json(read(&api).peers)
503}
504
505async fn network(State(api): State<Api>) -> Json<NetworkJson> {
507 let (name, description) = match read(&api).node.network_identifier {
508 104 => ("mainnet", "Symbol mainnet"),
509 152 => ("testnet", "Symbol testnet"),
510 _ => ("custom", "Symbol private network"),
511 };
512 Json(NetworkJson {
513 name: name.to_owned(),
514 description: description.to_owned(),
515 })
516}
517
518async fn network_properties(State(api): State<Api>) -> Json<NetworkPropertiesJson> {
519 Json(NetworkPropertiesJson::clone(&api.node.network_properties))
520}
521
522async fn node_server() -> Json<ServerInfoJson> {
524 let version = env!("CARGO_PKG_VERSION").to_owned();
525 Json(ServerInfoJson {
526 server_info: ServerJson {
527 rest_version: version.clone(),
528 deployment: DeploymentJson {
529 deployment_tool: "heika".to_owned(),
530 deployment_tool_version: version,
531 last_updated_date: "N/A".to_owned(),
532 },
533 },
534 })
535}
536
537async fn node_time(State(api): State<Api>) -> Json<NodeTimeJson> {
540 let now = network_millis(api.node.epoch, SystemTime::now()).to_string();
541 Json(NodeTimeJson {
542 communication_timestamps: CommunicationTimestampsJson {
543 send_timestamp: now.clone(),
544 receive_timestamp: now,
545 },
546 })
547}
548
549fn network_millis(epoch: SystemTime, now: SystemTime) -> u64 {
551 let elapsed = now.duration_since(epoch).unwrap_or_default().as_millis();
552 u64::try_from(elapsed).unwrap_or(u64::MAX)
553}
554
555async fn node_health() -> Json<NodeHealthJson> {
557 Json(NodeHealthJson {
558 status: HealthStatusJson {
559 api_node: "up".to_owned(),
560 db: "up".to_owned(),
561 },
562 })
563}
564
565async fn chain_info(State(api): State<Api>) -> Json<ChainInfoJson> {
566 Json(read(&api).chain)
567}
568
569async fn unlocked(State(api): State<Api>) -> Json<UnlockedAccountJson> {
570 Json(read(&api).unlocked)
571}
572
573async fn delegations(State(api): State<Api>) -> Json<Vec<DelegationJson>> {
574 Json(read(&api).delegations)
575}
576
577async fn announce_partial(State(api): State<Api>, Json(body): Json<AnnounceJson>) -> Response {
580 let result = match decode_hex(&body.payload) {
581 Some(bytes) => (api.node.submit_partial)(bytes),
582 None => Err("payload が16進ではありません".to_owned()),
583 };
584 match result {
585 Ok(()) => (
586 StatusCode::ACCEPTED,
587 Json(AnnounceResultJson::pushed_via(256, "/transactions/partial")),
588 )
589 .into_response(),
590 Err(message) => invalid(message),
591 }
592}
593
594async fn announce_cosignature(
596 State(api): State<Api>,
597 Json(body): Json<CosignatureJson>,
598) -> Response {
599 let version_ok = body
600 .version
601 .as_deref()
602 .is_none_or(|version| version.parse::<u64>() == Ok(0));
603 let parts = (
604 decode_hex(&body.signer_public_key).filter(|bytes| bytes.len() == 32),
605 decode_hex(&body.signature).filter(|bytes| bytes.len() == 64),
606 decode_hex(&body.parent_hash).filter(|bytes| bytes.len() == 32),
607 );
608 let result = match parts {
609 (Some(key), Some(signature), Some(parent)) if version_ok => {
610 let bytes = [&[0; 8][..], &key, &signature, &parent].concat();
611 (api.node.submit_cosignature)(bytes)
612 }
613 _ => Err("連署の形が正しくありません".to_owned()),
614 };
615 match result {
616 Ok(()) => (
617 StatusCode::ACCEPTED,
618 Json(AnnounceResultJson::pushed_via(
619 257,
620 "/transactions/cosignature",
621 )),
622 )
623 .into_response(),
624 Err(message) => invalid(message),
625 }
626}
627
628async fn announce(State(api): State<Api>, Json(body): Json<AnnounceJson>) -> Response {
629 let result = match decode_hex(&body.payload) {
630 Some(bytes) => (api.node.submit)(bytes),
631 None => Err("payload が16進ではありません".to_owned()),
632 };
633 match result {
634 Ok(()) => (StatusCode::ACCEPTED, Json(AnnounceResultJson::pushed())).into_response(),
635 Err(message) => invalid(message),
636 }
637}
638
639pub const MAX_BLOCK_BYTES: usize = 32 * 1024 * 1024;
642
643async fn announce_block(State(api): State<Api>, headers: HeaderMap, body: Bytes) -> Response {
648 let media = headers
649 .get(CONTENT_TYPE)
650 .and_then(|value| value.to_str().ok())
651 .and_then(|value| value.split(';').next())
652 .map(|value| value.trim().to_ascii_lowercase());
653 let bytes: Result<Vec<u8>, &str> = match media.as_deref() {
654 Some("application/octet-stream") => Ok(body.to_vec()),
655 Some("application/json") => match Json::<AnnounceJson>::from_bytes(&body) {
656 Ok(Json(body)) => decode_hex(&body.payload).ok_or("payload が16進ではありません"),
657 Err(rejection) => return rejection.into_response(),
658 },
659 _ => {
660 return error(
661 StatusCode::UNSUPPORTED_MEDIA_TYPE,
662 "UnsupportedMediaType",
663 "Content-Type は application/json か application/octet-stream にしてください"
664 .to_owned(),
665 );
666 }
667 };
668 if bytes
669 .as_ref()
670 .is_ok_and(|bytes| bytes.len() > MAX_BLOCK_BYTES)
671 {
672 return error(
673 StatusCode::PAYLOAD_TOO_LARGE,
674 "PayloadTooLarge",
675 format!("ブロックは {MAX_BLOCK_BYTES} バイトまでです"),
676 );
677 }
678 let result = bytes
679 .map_err(str::to_owned)
680 .and_then(|bytes| (api.node.submit_block)(bytes));
681 match result {
682 Ok(()) => (
683 StatusCode::ACCEPTED,
684 Json(AnnounceResultJson::pushed_via(3, "/blocks")),
685 )
686 .into_response(),
687 Err(message) => invalid(message),
688 }
689}
690
691async fn source_code() -> Response {
693 match offered_source() {
694 Some(zip) => (
695 [
696 (CONTENT_TYPE, "application/zip"),
697 (
698 CONTENT_DISPOSITION,
699 concat!(
700 "attachment; filename=\"heika-",
701 env!("CARGO_PKG_VERSION"),
702 ".zip\""
703 ),
704 ),
705 ],
706 zip,
707 )
708 .into_response(),
709 None => error(
710 StatusCode::NOT_FOUND,
711 "ResourceNotFound",
712 "このノードのバイナリには、ソースが入っていません".to_owned(),
713 ),
714 }
715}
716
717fn error(status: StatusCode, code: &str, message: String) -> Response {
719 let code = code.to_owned();
720 (status, Json(ErrorJson { code, message })).into_response()
721}
722
723fn invalid(message: String) -> Response {
724 error(StatusCode::CONFLICT, "InvalidArgument", message)
725}
726
727#[derive(Debug, Default, serde::Deserialize)]
729struct AtQuery {
730 height: Option<String>,
731}
732
733impl AtQuery {
734 fn at(&self) -> Result<Option<u64>, InvalidHeight> {
736 self.height
737 .as_deref()
738 .map(|height| block_height(height).ok_or(InvalidHeight))
739 .transpose()
740 }
741}
742
743const MAX_MULTISIG_LEVELS: i32 = 16;
745
746pub fn multisig_graph<E>(
750 address: &Address,
751 mut read: impl FnMut(&[Address]) -> Result<Vec<MultisigJson>, E>,
752) -> Result<Option<Vec<MultisigGraphLevel>>, E> {
753 let Some(start) = read(std::slice::from_ref(address))?.into_iter().next() else {
754 return Ok(None);
755 };
756 let next = |entries: &[MultisigJson], up: bool| {
758 let mut addresses: Vec<Address> = Vec::new();
759 for entry in entries {
760 let side = if up {
761 &entry.multisig_addresses
762 } else {
763 &entry.cosignatory_addresses
764 };
765 for address in side.iter().filter_map(|hex| Address::from_hex(hex).ok()) {
766 if !addresses.contains(&address) {
767 addresses.push(address);
768 }
769 }
770 }
771 addresses
772 };
773 let mut levels = vec![(0, vec![start])];
774 for up in [true, false] {
775 let step = if up { -1 } else { 1 };
776 let mut level: i32 = 0;
777 let mut entries = levels[if up { 0 } else { levels.len() - 1 }].1.clone();
778 while level.abs() < MAX_MULTISIG_LEVELS {
779 let addresses = next(&entries, up);
780 if addresses.is_empty() {
781 break;
782 }
783 entries = read(&addresses)?;
784 if entries.is_empty() {
785 break;
786 }
787 level += step;
788 if up {
789 levels.insert(0, (level, entries.clone()));
790 } else {
791 levels.push((level, entries.clone()));
792 }
793 }
794 }
795 Ok(Some(
796 levels
797 .into_iter()
798 .map(|(level, entries)| MultisigGraphLevel {
799 level,
800 multisig_entries: entries
801 .into_iter()
802 .map(|multisig| MultisigInfo { multisig })
803 .collect(),
804 })
805 .collect(),
806 ))
807}
808
809struct InvalidHeight;
811
812impl IntoResponse for InvalidHeight {
813 fn into_response(self) -> Response {
814 invalid("height has an invalid format".to_owned())
815 }
816}
817
818fn found_at<T: serde::Serialize>(
822 id: &str,
823 at: Option<u64>,
824 read: Result<Option<T>, StateError>,
825) -> Response {
826 let mut response = match read {
827 Ok(read) => found(id, Ok(read)),
828 Err(StateError::Ahead { height, tip }) => {
829 invalid(format!("height {height} is above the chain height {tip}"))
830 }
831 Err(StateError::NoHistory { height }) => error(
832 StatusCode::GONE,
833 "Gone",
834 format!("this node keeps no state history at height {height}"),
835 ),
836 Err(StateError::Invalid(message)) => invalid(message),
837 Err(StateError::Other(message)) => found::<T>(id, Err(message)),
838 };
839 if let Some(height) = at {
840 response
841 .headers_mut()
842 .insert(HEIGHT_HEADER, HeaderValue::from(height));
843 }
844 response
845}
846
847fn found<T: serde::Serialize>(id: &str, read: Result<Option<T>, String>) -> Response {
849 match read {
850 Ok(Some(value)) => Json(value).into_response(),
851 Ok(None) => error(
852 StatusCode::NOT_FOUND,
853 "ResourceNotFound",
854 format!("no resource exists with id '{id}'"),
855 ),
856 Err(message) => error(StatusCode::INTERNAL_SERVER_ERROR, "Internal", message),
857 }
858}
859
860fn account_address(id: &str, network: NetworkIdentifier) -> Option<Address> {
862 if id.len() == 64 {
863 let key: PublicKey = id.parse().ok()?;
864 return Some(Address::from_public_key(&key, network));
865 }
866 let address = id.parse().or_else(|_| Address::from_hex(id)).ok()?;
867 (address.network() == network).then_some(address)
868}
869
870fn hex_id(id: &str) -> Option<u64> {
872 (id.len() == 16)
873 .then(|| u64::from_str_radix(id, 16).ok())
874 .flatten()
875}
876
877async fn account(
878 State(api): State<Api>,
879 Path(id): Path<String>,
880 Query(query): Query<AtQuery>,
881) -> Response {
882 let Some(address) = account_address(&id, api.node.reader.network()) else {
883 return invalid("accountId has an invalid format".to_owned());
884 };
885 let at = match query.at() {
886 Ok(at) => at,
887 Err(invalid) => return invalid.into_response(),
888 };
889 let read = api.node.reader.accounts(&[address], at);
890 found_at(
891 &id,
892 at,
893 read.map(|accounts| {
894 accounts
895 .into_iter()
896 .next()
897 .map(|account| AccountInfo { account })
898 }),
899 )
900}
901
902#[derive(Debug, Default, serde::Deserialize)]
904#[serde(rename_all = "camelCase")]
905struct StatesBody {
906 addresses: Option<OneOrMany>,
907 public_keys: Option<OneOrMany>,
908 mosaic_ids: Option<OneOrMany>,
909}
910
911#[derive(Debug, serde::Deserialize)]
912#[serde(untagged)]
913enum OneOrMany {
914 One(String),
915 Many(Vec<String>),
916}
917
918impl OneOrMany {
919 fn into_vec(self) -> Vec<String> {
920 match self {
921 OneOrMany::One(value) => vec![value],
922 OneOrMany::Many(values) => values,
923 }
924 }
925}
926
927fn dedup<T: PartialEq>(values: Vec<T>) -> Vec<T> {
929 let mut out: Vec<T> = Vec::with_capacity(values.len());
930 for value in values {
931 if !out.contains(&value) {
932 out.push(value);
933 }
934 }
935 out
936}
937
938async fn accounts(
940 State(api): State<Api>,
941 Query(query): Query<AtQuery>,
942 Json(body): Json<StatesBody>,
943) -> Response {
944 let network = api.node.reader.network();
945 let ids = match (body.addresses, body.public_keys) {
946 (Some(_), Some(_)) => {
947 return invalid("publicKeys and addresses cannot both be provided".to_owned());
948 }
949 (None, Some(keys)) => {
950 body_ids(Some(&keys.into_vec()), "publicKeys", MAX_STATE_IDS, |key| {
951 (key.len() == 64)
952 .then(|| account_address(key, network))
953 .flatten()
954 })
955 }
956 (addresses, None) => body_ids(
957 addresses.map(OneOrMany::into_vec).as_deref(),
958 "addresses",
959 MAX_STATE_IDS,
960 |id| address_only(id, network),
961 ),
962 };
963 let addresses = match ids {
964 Ok(addresses) => dedup(addresses),
965 Err(message) => return invalid(message),
966 };
967 let at = match query.at() {
968 Ok(at) => at,
969 Err(invalid) => return invalid.into_response(),
970 };
971 let read = api.node.reader.accounts(&addresses, at).map(|accounts| {
972 accounts
973 .into_iter()
974 .map(|account| AccountInfo { account })
975 .collect::<Vec<_>>()
976 });
977 found_at("", at, read.map(Some))
978}
979
980async fn account_merkle(
981 State(api): State<Api>,
982 Path(id): Path<String>,
983 Query(query): Query<AtQuery>,
984) -> Response {
985 let Some(address) = account_address(&id, api.node.reader.network()) else {
986 return invalid("accountId has an invalid format".to_owned());
987 };
988 state_path(
989 &api,
990 &id,
991 &query,
992 SubCache::AccountState,
993 patricia::address_key(&address),
994 )
995}
996
997async fn mosaic(
998 State(api): State<Api>,
999 Path(id): Path<String>,
1000 Query(query): Query<AtQuery>,
1001) -> Response {
1002 let Some(mosaic_id) = hex_id(&id) else {
1003 return invalid("mosaicId has an invalid format".to_owned());
1004 };
1005 let at = match query.at() {
1006 Ok(at) => at,
1007 Err(invalid) => return invalid.into_response(),
1008 };
1009 let read = api.node.reader.mosaics(&[mosaic_id], at);
1010 found_at(
1011 &id,
1012 at,
1013 read.map(|mosaics| {
1014 mosaics
1015 .into_iter()
1016 .next()
1017 .map(|mosaic| MosaicInfo { mosaic })
1018 }),
1019 )
1020}
1021
1022async fn mosaics(
1024 State(api): State<Api>,
1025 Query(query): Query<AtQuery>,
1026 Json(body): Json<StatesBody>,
1027) -> Response {
1028 let ids = match body_ids(
1029 body.mosaic_ids.map(OneOrMany::into_vec).as_deref(),
1030 "mosaicIds",
1031 MAX_STATE_IDS,
1032 hex_id,
1033 ) {
1034 Ok(ids) => dedup(ids),
1035 Err(message) => return invalid(message),
1036 };
1037 let at = match query.at() {
1038 Ok(at) => at,
1039 Err(invalid) => return invalid.into_response(),
1040 };
1041 let read = api.node.reader.mosaics(&ids, at).map(|mosaics| {
1042 mosaics
1043 .into_iter()
1044 .map(|mosaic| MosaicInfo { mosaic })
1045 .collect::<Vec<_>>()
1046 });
1047 found_at("", at, read.map(Some))
1048}
1049
1050async fn multisig(
1051 State(api): State<Api>,
1052 Path(id): Path<String>,
1053 Query(query): Query<AtQuery>,
1054) -> Response {
1055 let Some(address) = address_only(&id, api.node.reader.network()) else {
1056 return invalid("address has an invalid format".to_owned());
1057 };
1058 let at = match query.at() {
1059 Ok(at) => at,
1060 Err(invalid) => return invalid.into_response(),
1061 };
1062 let read = api.node.reader.multisigs(&[address], at);
1063 found_at(
1064 &id,
1065 at,
1066 read.map(|entries| {
1067 entries
1068 .into_iter()
1069 .next()
1070 .map(|multisig| MultisigInfo { multisig })
1071 }),
1072 )
1073}
1074
1075async fn multisig_merkle(
1076 State(api): State<Api>,
1077 Path(id): Path<String>,
1078 Query(query): Query<AtQuery>,
1079) -> Response {
1080 let Some(address) = address_only(&id, api.node.reader.network()) else {
1081 return invalid("address has an invalid format".to_owned());
1082 };
1083 state_path(
1084 &api,
1085 &id,
1086 &query,
1087 SubCache::Multisig,
1088 patricia::address_key(&address),
1089 )
1090}
1091
1092async fn multisig_graph_route(
1093 State(api): State<Api>,
1094 Path(id): Path<String>,
1095 Query(query): Query<AtQuery>,
1096) -> Response {
1097 let Some(address) = address_only(&id, api.node.reader.network()) else {
1098 return invalid("address has an invalid format".to_owned());
1099 };
1100 let at = match query.at() {
1101 Ok(at) => at,
1102 Err(invalid) => return invalid.into_response(),
1103 };
1104 found_at(&id, at, api.node.reader.multisig_graph(&address, at))
1105}
1106
1107#[derive(Clone, Copy)]
1109enum Kept {
1110 HashLock,
1111 SecretLock,
1112 AccountRestriction,
1113 MosaicRestriction,
1114}
1115
1116impl Kept {
1117 fn cache(self) -> SubCache {
1118 match self {
1119 Kept::HashLock => SubCache::HashLockInfo,
1120 Kept::SecretLock => SubCache::SecretLockInfo,
1121 Kept::AccountRestriction => SubCache::AccountRestriction,
1122 Kept::MosaicRestriction => SubCache::MosaicRestriction,
1123 }
1124 }
1125
1126 fn names(self) -> (&'static str, &'static str) {
1128 match self {
1129 Kept::HashLock => ("hash", "hashes"),
1130 Kept::SecretLock | Kept::MosaicRestriction => ("compositeHash", "compositeHashes"),
1131 Kept::AccountRestriction => ("address", "addresses"),
1132 }
1133 }
1134
1135 fn key(self, id: &str, network: NetworkIdentifier) -> Option<Vec<u8>> {
1137 match self {
1138 Kept::AccountRestriction => address_only(id, network).map(|address| address.0.to_vec()),
1139 _ => hash256(id).map(|hash| hash.0.to_vec()),
1140 }
1141 }
1142
1143 fn tree_key(self, key: &[u8]) -> Hash256 {
1145 match self {
1146 Kept::AccountRestriction => {
1147 patricia::address_key(&Address(key.try_into().expect("24 バイト")))
1148 }
1149 _ => patricia::hash_key(&Hash256(key.try_into().expect("32 バイト"))),
1150 }
1151 }
1152
1153 fn json(self, key: &[u8], bytes: &[u8]) -> Result<KeptJson, String> {
1155 let hash = || Hash256(key.try_into().unwrap_or([0; 32]));
1156 match self {
1157 Kept::HashLock => HashLockJson::from_state_bytes(bytes)
1158 .map(|lock| KeptJson::HashLock(HashLockInfo { lock })),
1159 Kept::SecretLock => SecretLockJson::from_state_bytes(bytes, &hash())
1160 .map(|lock| KeptJson::SecretLock(SecretLockInfo { lock })),
1161 Kept::AccountRestriction => {
1162 AccountRestrictionsJson::from_state_bytes(bytes).map(|account_restrictions| {
1163 KeptJson::AccountRestriction(AccountRestrictionsInfo {
1164 account_restrictions,
1165 })
1166 })
1167 }
1168 Kept::MosaicRestriction => MosaicRestrictionEntryJson::from_state_bytes(bytes, &hash())
1169 .map(|mosaic_restriction_entry| {
1170 KeptJson::MosaicRestriction(MosaicRestrictionInfo {
1171 mosaic_restriction_entry,
1172 })
1173 }),
1174 }
1175 .map_err(|error| error.to_string())
1176 }
1177
1178 fn read(
1180 self,
1181 api: &Api,
1182 keys: &[Vec<u8>],
1183 at: Option<u64>,
1184 ) -> Result<Vec<KeptJson>, StateError> {
1185 api.node
1186 .reader
1187 .lock_or_restriction_states(self.cache(), keys, at)?
1188 .iter()
1189 .map(|(key, bytes)| self.json(key, bytes).map_err(StateError::Other))
1190 .collect()
1191 }
1192}
1193
1194#[derive(serde::Serialize)]
1196#[serde(untagged)]
1197enum KeptJson {
1198 HashLock(HashLockInfo),
1199 SecretLock(SecretLockInfo),
1200 AccountRestriction(AccountRestrictionsInfo),
1201 MosaicRestriction(MosaicRestrictionInfo),
1202}
1203
1204#[derive(Debug, Default, serde::Deserialize)]
1206#[serde(rename_all = "camelCase")]
1207struct KeptBody {
1208 hashes: Option<OneOrMany>,
1209 composite_hashes: Option<OneOrMany>,
1210 addresses: Option<OneOrMany>,
1211}
1212
1213async fn kept_one(kept: Kept, api: Api, id: String, query: AtQuery) -> Response {
1214 let Some(key) = kept.key(&id, api.node.reader.network()) else {
1215 return invalid(format!("{} has an invalid format", kept.names().0));
1216 };
1217 let at = match query.at() {
1218 Ok(at) => at,
1219 Err(invalid) => return invalid.into_response(),
1220 };
1221 let read = kept.read(&api, &[key], at);
1222 found_at(&id, at, read.map(|values| values.into_iter().next()))
1223}
1224
1225async fn kept_many(kept: Kept, api: Api, query: AtQuery, body: KeptBody) -> Response {
1226 let name = kept.names().1;
1227 let values = match kept {
1228 Kept::HashLock => body.hashes,
1229 Kept::SecretLock | Kept::MosaicRestriction => body.composite_hashes,
1230 Kept::AccountRestriction => body.addresses,
1231 }
1232 .map(OneOrMany::into_vec);
1233 let network = api.node.reader.network();
1234 let keys = match body_ids(values.as_deref(), name, MAX_STATE_IDS, |id| {
1235 kept.key(id, network)
1236 }) {
1237 Ok(keys) => dedup(keys),
1238 Err(message) => return invalid(message),
1239 };
1240 let at = match query.at() {
1241 Ok(at) => at,
1242 Err(invalid) => return invalid.into_response(),
1243 };
1244 found_at("", at, kept.read(&api, &keys, at).map(Some))
1245}
1246
1247async fn kept_merkle(kept: Kept, api: Api, id: String, query: AtQuery) -> Response {
1248 let Some(key) = kept.key(&id, api.node.reader.network()) else {
1249 return invalid(format!("{} has an invalid format", kept.names().0));
1250 };
1251 state_path(&api, &id, &query, kept.cache(), kept.tree_key(&key))
1252}
1253
1254fn kept_routes(router: Router<Api>, base: &str, kept: Kept) -> Router<Api> {
1256 let id = kept.names().0;
1257 router
1258 .route(
1259 base,
1260 post(
1261 move |State(api): State<Api>,
1262 Query(query): Query<AtQuery>,
1263 Json(body): Json<KeptBody>| {
1264 kept_many(kept, api, query, body)
1265 },
1266 )
1267 .options(preflight),
1268 )
1269 .route(
1270 &format!("{base}/{{{id}}}"),
1271 get(
1272 move |State(api): State<Api>,
1273 Path(id): Path<String>,
1274 Query(query): Query<AtQuery>| kept_one(kept, api, id, query),
1275 ),
1276 )
1277 .route(
1278 &format!("{base}/{{{id}}}/merkle"),
1279 get(
1280 move |State(api): State<Api>,
1281 Path(id): Path<String>,
1282 Query(query): Query<AtQuery>| {
1283 kept_merkle(kept, api, id, query)
1284 },
1285 ),
1286 )
1287}
1288
1289async fn mosaic_merkle(
1290 State(api): State<Api>,
1291 Path(id): Path<String>,
1292 Query(query): Query<AtQuery>,
1293) -> Response {
1294 let Some(mosaic_id) = hex_id(&id) else {
1295 return invalid("mosaicId has an invalid format".to_owned());
1296 };
1297 state_path(
1298 &api,
1299 &id,
1300 &query,
1301 SubCache::Mosaic,
1302 patricia::id_key(mosaic_id),
1303 )
1304}
1305
1306async fn namespace(
1307 State(api): State<Api>,
1308 Path(id): Path<String>,
1309 Query(query): Query<AtQuery>,
1310) -> Response {
1311 let Some(namespace_id) = hex_id(&id) else {
1312 return invalid("namespaceId has an invalid format".to_owned());
1313 };
1314 let at = match query.at() {
1315 Ok(at) => at,
1316 Err(invalid) => return invalid.into_response(),
1317 };
1318 found_at(&id, at, api.node.reader.namespace(namespace_id, at))
1319}
1320
1321async fn namespace_merkle(
1323 State(api): State<Api>,
1324 Path(id): Path<String>,
1325 Query(query): Query<AtQuery>,
1326) -> Response {
1327 let Some(namespace_id) = hex_id(&id) else {
1328 return invalid("namespaceId has an invalid format".to_owned());
1329 };
1330 state_path(
1331 &api,
1332 &id,
1333 &query,
1334 SubCache::Namespace,
1335 patricia::id_key(namespace_id),
1336 )
1337}
1338
1339async fn metadata(
1340 State(api): State<Api>,
1341 Path(hash): Path<String>,
1342 Query(query): Query<AtQuery>,
1343) -> Response {
1344 let Some(composite_hash) = hash256(&hash) else {
1345 return invalid("compositeHash has an invalid format".to_owned());
1346 };
1347 let at = match query.at() {
1348 Ok(at) => at,
1349 Err(invalid) => return invalid.into_response(),
1350 };
1351 let read = api.node.reader.metadata(&composite_hash, at);
1352 found_at(
1353 &hash,
1354 at,
1355 read.map(|entry| {
1356 entry.map(|metadata_entry| MetadataInfo {
1357 id: Some(metadata_entry.position()),
1358 metadata_entry,
1359 })
1360 }),
1361 )
1362}
1363
1364async fn metadata_merkle(
1365 State(api): State<Api>,
1366 Path(hash): Path<String>,
1367 Query(query): Query<AtQuery>,
1368) -> Response {
1369 let Some(composite_hash) = hash256(&hash) else {
1370 return invalid("compositeHash has an invalid format".to_owned());
1371 };
1372 state_path(
1373 &api,
1374 &hash,
1375 &query,
1376 SubCache::Metadata,
1377 patricia::hash_key(&composite_hash),
1378 )
1379}
1380
1381fn state_path(api: &Api, id: &str, query: &AtQuery, cache: SubCache, key: Hash256) -> Response {
1383 let at = match query.at() {
1384 Ok(at) => at,
1385 Err(invalid) => return invalid.into_response(),
1386 };
1387 found_at(
1388 id,
1389 at,
1390 api.node.reader.state_path(cache, &key, at).map(Some),
1391 )
1392}
1393
1394fn block_height(height: &str) -> Option<u64> {
1395 height.parse::<u64>().ok().filter(|&height| height > 0)
1396}
1397
1398#[derive(Debug, Default, serde::Deserialize)]
1400#[serde(rename_all = "camelCase")]
1401struct BlockQuery {
1402 page_size: Option<usize>,
1403 page_number: Option<usize>,
1404 order: Option<String>,
1405 order_by: Option<String>,
1406 offset: Option<String>,
1407 signer_public_key: Option<String>,
1408 beneficiary_address: Option<String>,
1409 from_timestamp: Option<String>,
1410 to_timestamp: Option<String>,
1411}
1412
1413async fn search_blocks(State(api): State<Api>, Query(query): Query<BlockQuery>) -> Response {
1417 if query.signer_public_key.is_some()
1418 || query.beneficiary_address.is_some()
1419 || query.from_timestamp.is_some()
1420 || query.to_timestamp.is_some()
1421 {
1422 return error(
1423 StatusCode::NOT_IMPLEMENTED,
1424 "NotImplemented",
1425 "this node does not filter blocks yet (only paging by height)".to_owned(),
1426 );
1427 }
1428 if let Some(field) = query
1429 .order_by
1430 .as_deref()
1431 .filter(|field| !matches!(*field, "id" | "height"))
1432 {
1433 return invalid(format!("sorting by {field} is not allowed"));
1434 }
1435 let page = match page_request(query.order.as_deref(), query.page_size, query.page_number) {
1436 Ok(page) => page,
1437 Err(message) => return invalid(message),
1438 };
1439 let offset = match query.offset.as_deref().map(str::parse::<u64>) {
1440 None => None,
1441 Some(Ok(offset)) => Some(offset),
1442 Some(Err(_)) => return invalid("offset has an invalid format".to_owned()),
1443 };
1444 let tip = read(&api).chain.height.parse::<u64>().unwrap_or(0);
1445 let skip = ((page.number - 1) * page.size) as u64;
1446 let heights: Vec<u64> = if page.descending {
1447 let below = offset.map_or(tip, |offset| offset.saturating_sub(1).min(tip));
1448 (1..=below.saturating_sub(skip))
1449 .rev()
1450 .take(page.size)
1451 .collect()
1452 } else {
1453 let above = offset.unwrap_or(0).saturating_add(1).saturating_add(skip);
1454 (above..=tip).take(page.size).collect()
1455 };
1456 let mut data = Vec::with_capacity(heights.len());
1457 for height in heights {
1458 match api.node.reader.block(height) {
1459 Ok(Some(block)) => data.push(block),
1460 Ok(None) => {}
1461 Err(message) => return error(StatusCode::INTERNAL_SERVER_ERROR, "Internal", message),
1462 }
1463 }
1464 Json(Page {
1465 data,
1466 pagination: Pagination {
1467 page_number: page.number,
1468 page_size: page.size,
1469 },
1470 })
1471 .into_response()
1472}
1473
1474async fn block(State(api): State<Api>, Path(height): Path<String>) -> Response {
1475 let Some(number) = block_height(&height) else {
1476 return invalid("height has an invalid format".to_owned());
1477 };
1478 found(&height, api.node.reader.block(number))
1479}
1480
1481async fn finalization_proof(State(api): State<Api>, Path(epoch): Path<String>) -> Response {
1482 let Some(number) = epoch
1484 .bytes()
1485 .all(|byte| byte.is_ascii_digit())
1486 .then(|| epoch.parse::<u32>().ok())
1487 .flatten()
1488 else {
1489 return invalid("epoch has an invalid format".to_owned());
1490 };
1491 let proof = api
1492 .node
1493 .reader
1494 .finalization_proof(number)
1495 .and_then(|proof| {
1496 proof
1497 .map(|bytes| {
1498 FinalizationProof::from_bytes(&bytes)
1499 .ok_or_else(|| format!("エポック {number} の証明が読めません"))
1500 })
1501 .transpose()
1502 });
1503 found(&epoch, proof)
1504}
1505
1506fn hash256(hash: &str) -> Option<Hash256> {
1508 if hash.len() != 64 {
1509 return None;
1510 }
1511 let mut bytes = [0; 32];
1512 base16ct::mixed::decode(hash, &mut bytes).ok()?;
1513 Some(Hash256(bytes))
1514}
1515
1516async fn partial_transaction(State(api): State<Api>, Path(hash): Path<String>) -> Response {
1517 let Some(key) = hash256(&hash) else {
1518 return invalid("transactionId has an invalid format".to_owned());
1519 };
1520 found(&hash, api.node.reader.partial_transaction(&key))
1521}
1522
1523async fn unconfirmed_transaction(State(api): State<Api>, Path(hash): Path<String>) -> Response {
1524 let Some(key) = hash256(&hash) else {
1525 return invalid("transactionId has an invalid format".to_owned());
1526 };
1527 found(&hash, api.node.reader.unconfirmed_transaction(&key))
1528}
1529
1530fn address_only(id: &str, network: NetworkIdentifier) -> Option<Address> {
1533 (id.len() != 64)
1534 .then(|| account_address(id, network))
1535 .flatten()
1536}
1537
1538async fn search_metadata(State(api): State<Api>, Query(query): Query<MetadataQuery>) -> Response {
1539 let network = api.node.reader.network();
1540 let address = |value: &Option<String>, name: &'static str| match value.as_deref() {
1542 None => Ok(None),
1543 Some(id) => address_only(id, network).map(Some).ok_or(name),
1544 };
1545 let id = |value: &Option<String>, name: &'static str| match value.as_deref() {
1546 None => Ok(None),
1547 Some(id) => hex_id(id).map(Some).ok_or(name),
1548 };
1549 let filter = (|| {
1550 Ok::<_, &str>(MetadataFilter {
1551 source: address(&query.source_address, "sourceAddress")?,
1552 target: address(&query.target_address, "targetAddress")?,
1553 scoped_key: id(&query.scoped_metadata_key, "scopedMetadataKey")?,
1554 target_id: id(&query.target_id, "targetId")?,
1555 metadata_type: query.metadata_type,
1556 })
1557 })();
1558 let filter = match filter {
1559 Ok(filter) => filter,
1560 Err(name) => return invalid(format!("{name} has an invalid format")),
1561 };
1562 let at = match (AtQuery {
1563 height: query.height.clone(),
1564 })
1565 .at()
1566 {
1567 Ok(at) => at,
1568 Err(invalid) => return invalid.into_response(),
1569 };
1570 let after = match query.offset.as_deref().map(MetadataPosition::parse) {
1572 None => None,
1573 Some(Some(position)) => Some(position),
1574 Some(None) => return invalid("offset has an invalid format".to_owned()),
1575 };
1576 let page = match page_request(query.order.as_deref(), query.page_size, query.page_number) {
1577 Ok(page) => page,
1578 Err(message) => return invalid(message),
1579 };
1580 let read = api
1581 .node
1582 .reader
1583 .search_metadata(&filter, page, after.as_ref(), at);
1584 if let Ok(None) = read {
1585 return search_not_kept("metadata", at);
1586 }
1587 found_at(
1589 "metadata",
1590 at,
1591 read.map(|entries| {
1592 entries.map(|entries| Page {
1593 data: entries
1594 .into_iter()
1595 .map(|metadata_entry| MetadataInfo {
1596 id: Some(metadata_entry.position()),
1597 metadata_entry,
1598 })
1599 .collect(),
1600 pagination: Pagination {
1601 page_number: page.number,
1602 page_size: page.size,
1603 },
1604 })
1605 }),
1606 )
1607}
1608
1609async fn search_confirmed(
1612 State(api): State<Api>,
1613 Query(query): Query<TransactionQuery>,
1614 RawQuery(raw): RawQuery,
1615) -> Response {
1616 if query.address.is_some()
1617 && (query.signer_public_key.is_some() || query.recipient_address.is_some())
1618 {
1619 return invalid(
1620 "can't filter by address if signerPublicKey or recipientAddress are already provided"
1621 .to_owned(),
1622 );
1623 }
1624 if (query.from_transfer_amount.is_some() || query.to_transfer_amount.is_some())
1625 && query.transfer_mosaic_id.is_none()
1626 {
1627 return invalid(
1628 "can't filter by transfer amount if transferMosaicId is not provided".to_owned(),
1629 );
1630 }
1631 let network = api.node.reader.network();
1632 let filter = (|| {
1633 let number = |value: &Option<String>, name: &str| match value.as_deref() {
1634 None => Ok(None),
1635 Some(text) => text
1636 .parse::<u64>()
1637 .map(Some)
1638 .map_err(|_| format!("{name} has an invalid format")),
1639 };
1640 let address = |value: &Option<String>, name: &str| match value.as_deref() {
1641 None => Ok(None),
1642 Some(id) => address_only(id, network)
1643 .map(Some)
1644 .ok_or_else(|| format!("{name} has an invalid format")),
1645 };
1646 let exact = number(&query.height, "height")?;
1647 Ok::<_, String>(TransactionFilter {
1648 address: address(&query.address, "address")?,
1649 signer: match query.signer_public_key.as_deref() {
1650 None => None,
1651 Some(key) => Some(
1652 key.parse::<PublicKey>()
1653 .ok()
1654 .filter(|_| key.len() == 64)
1655 .ok_or("signerPublicKey has an invalid format")?,
1656 ),
1657 },
1658 recipient: address(&query.recipient_address, "recipientAddress")?.map(|a| a.0),
1659 types: transaction_types(raw.as_deref()).ok_or("type has an invalid format")?,
1660 mosaic: match query.transfer_mosaic_id.as_deref() {
1661 None => None,
1662 Some(id) => Some(hex_id(id).ok_or("transferMosaicId has an invalid format")?),
1663 },
1664 from_amount: number(&query.from_transfer_amount, "fromTransferAmount")?,
1665 to_amount: number(&query.to_transfer_amount, "toTransferAmount")?,
1666 from_height: exact
1667 .or(number(&query.from_height, "fromHeight")?)
1668 .unwrap_or(0),
1669 to_height: exact
1670 .or(number(&query.to_height, "toHeight")?)
1671 .unwrap_or(u64::MAX),
1672 embedded: match query.embedded.as_deref() {
1673 None | Some("false") => false,
1674 Some("true") => true,
1675 Some(_) => return Err("embedded has an invalid format".to_owned()),
1676 },
1677 })
1678 })();
1679 let filter = match filter {
1680 Ok(filter) => filter,
1681 Err(message) => return invalid(message),
1682 };
1683 let after = match query.offset.as_deref().map(parse_transaction_position) {
1685 None => None,
1686 Some(Some(position)) => Some(position),
1687 Some(None) => return invalid("offset has an invalid format".to_owned()),
1688 };
1689 let page = match page_request(query.order.as_deref(), query.page_size, query.page_number) {
1690 Ok(page) => page,
1691 Err(message) => return invalid(message),
1692 };
1693 match api.node.reader.search_transactions(&filter, page, after) {
1694 Ok(None) => search_not_kept("transaction", None),
1695 Ok(Some(data)) => Json(Page {
1696 data,
1697 pagination: Pagination {
1698 page_number: page.number,
1699 page_size: page.size,
1700 },
1701 })
1702 .into_response(),
1703 Err(message) => error(StatusCode::INTERNAL_SERVER_ERROR, "Internal", message),
1704 }
1705}
1706
1707fn page_request(
1709 order: Option<&str>,
1710 size: Option<usize>,
1711 number: Option<usize>,
1712) -> Result<PageRequest, String> {
1713 let descending = match order {
1714 None | Some("asc") => false,
1715 Some("desc") => true,
1716 Some(_) => return Err("order has an invalid format".to_owned()),
1717 };
1718 Ok(PageRequest {
1719 size: size.unwrap_or(10).clamp(10, 100),
1720 number: number.unwrap_or(1).max(1),
1721 descending,
1722 })
1723}
1724
1725fn search_not_kept(what: &str, at: Option<u64>) -> Response {
1727 let scope = if at.is_some() {
1728 "at past heights (storage.search on an archive node)"
1729 } else {
1730 "(storage.search)"
1731 };
1732 error(
1733 StatusCode::NOT_IMPLEMENTED,
1734 "NotImplemented",
1735 format!("this node does not keep the {what} search {scope}"),
1736 )
1737}
1738
1739async fn search_namespaces(
1740 State(api): State<Api>,
1741 Query(query): Query<NamespaceQuery>,
1742) -> Response {
1743 let network = api.node.reader.network();
1744 let owner = match query.owner_address.as_deref() {
1745 None => None,
1746 Some(id) => match address_only(id, network) {
1747 Some(address) => Some(address),
1748 None => return invalid("ownerAddress has an invalid format".to_owned()),
1749 },
1750 };
1751 let level0 = match query.level0.as_deref() {
1752 None => None,
1753 Some(id) => match hex_id(id) {
1754 Some(id) => Some(id),
1755 None => return invalid("level0 has an invalid format".to_owned()),
1756 },
1757 };
1758 let at = match (AtQuery {
1759 height: query.height.clone(),
1760 })
1761 .at()
1762 {
1763 Ok(at) => at,
1764 Err(invalid) => return invalid.into_response(),
1765 };
1766 let after = match query.offset.as_deref().map(decode_hex) {
1768 None => None,
1769 Some(Some(after)) if !after.is_empty() => Some(after),
1770 Some(_) => return invalid("offset has an invalid format".to_owned()),
1771 };
1772 let page = match page_request(query.order.as_deref(), query.page_size, query.page_number) {
1773 Ok(page) => page,
1774 Err(message) => return invalid(message),
1775 };
1776 let filter = NamespaceFilter {
1777 owner,
1778 level0,
1779 registration_type: query.registration_type,
1780 alias_type: query.alias_type,
1781 };
1782 let read = api
1783 .node
1784 .reader
1785 .search_namespaces(&filter, page, after.as_deref(), at);
1786 if let Ok(None) = read {
1787 return search_not_kept("namespace", at);
1788 }
1789 found_at(
1790 "namespaces",
1791 at,
1792 read.map(|entries| {
1793 entries.map(|entries| Page {
1794 data: entries
1795 .into_iter()
1796 .map(|(id, info)| NamespaceInfo {
1797 id: Some(id),
1798 ..info
1799 })
1800 .collect(),
1801 pagination: Pagination {
1802 page_number: page.number,
1803 page_size: page.size,
1804 },
1805 })
1806 }),
1807 )
1808}
1809
1810#[derive(Debug, Default, serde::Deserialize)]
1812#[serde(rename_all = "camelCase")]
1813struct NamesBody {
1814 namespace_ids: Option<Vec<String>>,
1815 addresses: Option<Vec<String>>,
1816 mosaic_ids: Option<Vec<String>>,
1817}
1818
1819fn name_ids<T>(
1821 values: Option<&[String]>,
1822 name: &str,
1823 parse: impl Fn(&str) -> Option<T>,
1824) -> Result<Vec<T>, String> {
1825 body_ids(values, name, MAX_NAME_IDS, parse)
1826}
1827
1828fn body_ids<T>(
1830 values: Option<&[String]>,
1831 name: &str,
1832 max: usize,
1833 parse: impl Fn(&str) -> Option<T>,
1834) -> Result<Vec<T>, String> {
1835 let values = values.ok_or_else(|| format!("{name} is missing"))?;
1836 if values.len() > max {
1837 return Err(format!("{name} has more than {max} items"));
1838 }
1839 values
1840 .iter()
1841 .map(|value| parse(value).ok_or_else(|| format!("{name} has an invalid format")))
1842 .collect()
1843}
1844
1845#[derive(serde::Serialize)]
1846#[serde(rename_all = "camelCase")]
1847struct AccountNamesPage {
1848 account_names: Vec<AccountNamesJson>,
1849}
1850
1851#[derive(serde::Serialize)]
1852#[serde(rename_all = "camelCase")]
1853struct MosaicNamesPage {
1854 mosaic_names: Vec<MosaicNamesJson>,
1855}
1856
1857fn names_response<T: serde::Serialize>(read: Result<Option<T>, String>) -> Response {
1858 match read {
1859 Ok(Some(value)) => Json(value).into_response(),
1860 Ok(None) => search_not_kept("namespace name", None),
1861 Err(message) => error(StatusCode::INTERNAL_SERVER_ERROR, "Internal", message),
1862 }
1863}
1864
1865async fn namespace_names(State(api): State<Api>, Json(body): Json<NamesBody>) -> Response {
1866 match name_ids(body.namespace_ids.as_deref(), "namespaceIds", hex_id) {
1867 Ok(ids) => names_response(api.node.reader.namespace_names(&ids)),
1868 Err(message) => invalid(message),
1869 }
1870}
1871
1872async fn account_names(State(api): State<Api>, Json(body): Json<NamesBody>) -> Response {
1873 let network = api.node.reader.network();
1874 let addresses = match name_ids(body.addresses.as_deref(), "addresses", |id| {
1875 address_only(id, network)
1876 }) {
1877 Ok(addresses) => addresses,
1878 Err(message) => return invalid(message),
1879 };
1880 let mut out = Vec::with_capacity(addresses.len());
1881 for address in addresses {
1882 match api.node.reader.alias_names(AliasTarget::Address(address)) {
1883 Ok(Some(names)) => out.push(AccountNamesJson {
1884 address: address.to_hex(),
1885 names,
1886 }),
1887 other => return names_response(other.map(|_| None::<()>)),
1888 }
1889 }
1890 Json(AccountNamesPage { account_names: out }).into_response()
1891}
1892
1893async fn mosaic_names(State(api): State<Api>, Json(body): Json<NamesBody>) -> Response {
1894 let ids = match name_ids(body.mosaic_ids.as_deref(), "mosaicIds", hex_id) {
1895 Ok(ids) => ids,
1896 Err(message) => return invalid(message),
1897 };
1898 let mut out = Vec::with_capacity(ids.len());
1899 for id in ids {
1900 match api.node.reader.alias_names(AliasTarget::Mosaic(id)) {
1901 Ok(Some(names)) => out.push(MosaicNamesJson {
1902 mosaic_id: format!("{id:016X}"),
1903 names,
1904 }),
1905 other => return names_response(other.map(|_| None::<()>)),
1906 }
1907 }
1908 Json(MosaicNamesPage { mosaic_names: out }).into_response()
1909}
1910
1911async fn partial_transactions(
1912 State(api): State<Api>,
1913 Query(query): Query<PartialQuery>,
1914) -> Response {
1915 list_pool(&api, &query, |filter| {
1916 api.node.reader.partial_transactions(filter)
1917 })
1918}
1919
1920async fn unconfirmed_transactions(
1922 State(api): State<Api>,
1923 Query(query): Query<PartialQuery>,
1924) -> Response {
1925 let embedded = match query.embedded.as_deref() {
1926 None | Some("false") => false,
1927 Some("true") => true,
1928 Some(_) => return invalid("embedded has an invalid format".to_owned()),
1929 };
1930 list_pool(&api, &query, |filter| {
1931 api.node.reader.unconfirmed_transactions(filter, embedded)
1932 })
1933}
1934
1935fn list_pool(
1937 api: &Api,
1938 query: &PartialQuery,
1939 read: impl FnOnce(&PartialFilter) -> Result<Vec<TransactionInfo>, String>,
1940) -> Response {
1941 let network = api.node.reader.network();
1942 let address = match query
1943 .address
1944 .as_deref()
1945 .map(|id| account_address(id, network))
1946 {
1947 None => None,
1948 Some(Some(address)) => Some(address),
1949 Some(None) => return invalid("address has an invalid format".to_owned()),
1950 };
1951 let signer = match query
1952 .signer_public_key
1953 .as_deref()
1954 .map(str::parse::<PublicKey>)
1955 {
1956 None => None,
1957 Some(Ok(key)) => Some(key),
1958 Some(Err(_)) => return invalid("signerPublicKey has an invalid format".to_owned()),
1959 };
1960 let page_size = query.page_size.unwrap_or(10).clamp(10, 100);
1961 let page_number = query.page_number.unwrap_or(1).max(1);
1962 match read(&PartialFilter { address, signer }) {
1963 Ok(all) => Json(Page {
1964 data: all
1965 .into_iter()
1966 .skip((page_number - 1) * page_size)
1967 .take(page_size)
1968 .collect(),
1969 pagination: Pagination {
1970 page_number,
1971 page_size,
1972 },
1973 })
1974 .into_response(),
1975 Err(message) => error(StatusCode::INTERNAL_SERVER_ERROR, "Internal", message),
1976 }
1977}
1978
1979async fn transaction_fees(State(api): State<Api>) -> Response {
1980 found("transaction", api.node.reader.transaction_fees().map(Some))
1981}
1982
1983async fn transaction_status(State(api): State<Api>, Path(hash): Path<String>) -> Response {
1984 let Some(key) = hash256(&hash) else {
1985 return invalid("hash has an invalid format".to_owned());
1986 };
1987 found(&hash, api.node.reader.transaction_status(&key))
1988}
1989
1990async fn confirmed_transaction(State(api): State<Api>, Path(hash): Path<String>) -> Response {
1991 let Some(key) = hash256(&hash) else {
1992 return invalid("transactionId has an invalid format".to_owned());
1993 };
1994 found(&hash, api.node.reader.confirmed_transaction(&key))
1995}
1996
1997async fn transaction_merkle(
1998 State(api): State<Api>,
1999 Path((height, hash)): Path<(String, String)>,
2000) -> Response {
2001 let (Some(number), Some(key)) = (block_height(&height), hash256(&hash)) else {
2002 return invalid("height or hash has an invalid format".to_owned());
2003 };
2004 found(&hash, api.node.reader.transaction_merkle(number, &key))
2005}
2006
2007fn decode_hex(text: &str) -> Option<Vec<u8>> {
2008 if text.is_empty() || !text.len().is_multiple_of(2) {
2010 return None;
2011 }
2012 let mut bytes = vec![0; text.len() / 2];
2013 base16ct::mixed::decode(text, &mut bytes).ok()?;
2014 Some(bytes)
2015}
2016
2017async fn preflight() -> StatusCode {
2019 StatusCode::NO_CONTENT
2020}
2021
2022async fn allow_any_origin(mut response: Response) -> Response {
2023 let headers = response.headers_mut();
2024 headers.insert(ACCESS_CONTROL_ALLOW_ORIGIN, HeaderValue::from_static("*"));
2025 headers.insert(
2026 ACCESS_CONTROL_ALLOW_METHODS,
2027 HeaderValue::from_static("GET, PUT, POST, OPTIONS"),
2028 );
2029 headers.insert(
2030 ACCESS_CONTROL_ALLOW_HEADERS,
2031 HeaderValue::from_static("Content-Type"),
2032 );
2033 response
2034}
2035
2036pub fn router(shared: Shared, node: Node) -> Router {
2038 let router = [
2039 ("/lock/hash", Kept::HashLock),
2040 ("/lock/secret", Kept::SecretLock),
2041 ("/restrictions/account", Kept::AccountRestriction),
2042 ("/restrictions/mosaic", Kept::MosaicRestriction),
2043 ]
2044 .into_iter()
2045 .fold(Router::new(), |router, (base, kept)| {
2046 kept_routes(router, base, kept)
2047 });
2048 router
2049 .route("/node/info", get(node_info))
2050 .route("/node/peers", get(node_peers))
2051 .route("/chain/info", get(chain_info))
2052 .route("/network", get(network))
2053 .route("/network/properties", get(network_properties))
2054 .route("/node/server", get(node_server))
2055 .route("/node/health", get(node_health))
2056 .route("/node/time", get(node_time))
2057 .route("/node/unlockedaccount", get(unlocked))
2058 .route("/heika/delegations", get(delegations))
2059 .route("/heika/sourcecode.zip", get(source_code))
2060 .route("/transactions", put(announce).options(preflight))
2061 .route(
2062 "/blocks",
2063 get(search_blocks)
2064 .put(announce_block)
2065 .options(preflight)
2066 .layer(DefaultBodyLimit::max(2 * MAX_BLOCK_BYTES + 1024)),
2068 )
2069 .route(
2070 "/transactions/partial",
2071 put(announce_partial)
2072 .get(partial_transactions)
2073 .options(preflight),
2074 )
2075 .route("/transactions/partial/{hash}", get(partial_transaction))
2076 .route("/transactions/unconfirmed", get(unconfirmed_transactions))
2077 .route(
2078 "/transactions/unconfirmed/{hash}",
2079 get(unconfirmed_transaction),
2080 )
2081 .route(
2082 "/transactions/cosignature",
2083 put(announce_cosignature).options(preflight),
2084 )
2085 .route("/accounts", post(accounts).options(preflight))
2086 .route("/accounts/{id}", get(account))
2087 .route("/accounts/{id}/merkle", get(account_merkle))
2088 .route("/account/{id}/multisig", get(multisig))
2089 .route("/account/{id}/multisig/merkle", get(multisig_merkle))
2090 .route("/account/{id}/multisig/graph", get(multisig_graph_route))
2091 .route("/mosaics", post(mosaics).options(preflight))
2092 .route("/mosaics/{id}", get(mosaic))
2093 .route("/mosaics/{id}/merkle", get(mosaic_merkle))
2094 .route("/namespaces", get(search_namespaces))
2095 .route(
2096 "/namespaces/names",
2097 post(namespace_names).options(preflight),
2098 )
2099 .route(
2100 "/namespaces/account/names",
2101 post(account_names).options(preflight),
2102 )
2103 .route(
2104 "/namespaces/mosaic/names",
2105 post(mosaic_names).options(preflight),
2106 )
2107 .route("/namespaces/{id}", get(namespace))
2108 .route("/namespaces/{id}/merkle", get(namespace_merkle))
2109 .route("/metadata", get(search_metadata))
2110 .route("/metadata/{hash}", get(metadata))
2111 .route("/metadata/{hash}/merkle", get(metadata_merkle))
2112 .route("/blocks/{height}", get(block))
2113 .route("/finalization/proof/epoch/{epoch}", get(finalization_proof))
2114 .route("/network/fees/transaction", get(transaction_fees))
2115 .route("/transactionStatus/{hash}", get(transaction_status))
2116 .route("/transactions/confirmed", get(search_confirmed))
2117 .route("/transactions/confirmed/{hash}", get(confirmed_transaction))
2118 .route(
2119 "/blocks/{height}/transactions/{hash}/merkle",
2120 get(transaction_merkle),
2121 )
2122 .layer(map_response(allow_any_origin))
2123 .with_state(Api { shared, node })
2124}
2125
2126#[derive(Clone, Debug, PartialEq, Eq)]
2128pub struct Listener {
2129 pub address: String,
2131 pub rate_limit: u32,
2133}
2134
2135struct Throttle {
2137 rate: f64,
2138 bucket: Mutex<(f64, Instant)>,
2139}
2140
2141impl Throttle {
2142 fn new(rate: u32, now: Instant) -> Self {
2143 let rate = f64::from(rate);
2144 Self {
2145 rate,
2146 bucket: Mutex::new((rate, now)),
2147 }
2148 }
2149
2150 fn take(&self, now: Instant) -> bool {
2152 let mut bucket = self
2153 .bucket
2154 .lock()
2155 .unwrap_or_else(|poisoned| poisoned.into_inner());
2156 let (tokens, last) = *bucket;
2157 let tokens =
2158 (tokens + now.saturating_duration_since(last).as_secs_f64() * self.rate).min(self.rate);
2159 let (tokens, taken) = if tokens >= 1.0 {
2160 (tokens - 1.0, true)
2161 } else {
2162 (tokens, false)
2163 };
2164 *bucket = (tokens, now);
2165 taken
2166 }
2167}
2168
2169pub fn limit(app: Router, rate: u32) -> Router {
2171 if rate == 0 {
2172 return app;
2173 }
2174 let throttle = Arc::new(Throttle::new(rate, Instant::now()));
2175 app.layer(from_fn(move |request: Request, next: Next| {
2176 let throttle = Arc::clone(&throttle);
2177 async move {
2178 if throttle.take(Instant::now()) {
2179 return next.run(request).await;
2180 }
2181 allow_any_origin(error(
2182 StatusCode::TOO_MANY_REQUESTS,
2183 "TooManyRequests",
2184 format!("1 秒に {rate} 回までです"),
2185 ))
2186 .await
2187 }
2188 }))
2189}
2190
2191pub fn serve(
2193 listeners: &[Listener],
2194 shared: Shared,
2195 node: Node,
2196 stop: Arc<AtomicBool>,
2197) -> Result<(), String> {
2198 let runtime = tokio::runtime::Builder::new_current_thread()
2199 .enable_io()
2200 .enable_time()
2201 .build()
2202 .map_err(|error| format!("API の tokio を動かせません: {error}"))?;
2203 runtime.block_on(async move {
2204 let mut tasks = tokio::task::JoinSet::new();
2205 for Listener {
2206 address,
2207 rate_limit,
2208 } in listeners
2209 {
2210 let listener = tokio::net::TcpListener::bind(address)
2211 .await
2212 .map_err(|error| format!("API を {address} で待ち受けられません: {error}"))?;
2213 println!("API を {address} で待ち受けます");
2214 let app = limit(router(Arc::clone(&shared), node.clone()), *rate_limit);
2215 let stop = Arc::clone(&stop);
2216 tasks.spawn(async move {
2217 axum::serve(listener, app)
2218 .with_graceful_shutdown(async move {
2219 while !stop.load(Ordering::SeqCst) {
2220 tokio::time::sleep(STOP_POLL).await;
2221 }
2222 })
2223 .await
2224 });
2225 }
2226 while let Some(result) = tasks.join_next().await {
2227 match result {
2228 Ok(Ok(())) => {}
2229 Ok(Err(error)) => return Err(format!("API が止まりました: {error}")),
2230 Err(error) => return Err(format!("API が止まりました: {error}")),
2231 }
2232 }
2233 Ok(())
2234 })
2235}
2236
2237#[cfg(test)]
2238mod tests {
2239 use axum::body::Body;
2240 use axum::http::Request;
2241 use heika_rest::node::DelegationStateJson;
2242 use http_body_util::BodyExt;
2243 use tower::ServiceExt;
2244
2245 use super::*;
2246
2247 fn snapshot() -> Shared {
2248 Arc::new(RwLock::new(Snapshot {
2249 node: NodeInfoJson {
2250 version: 0x0100_0309,
2251 public_key: "AA".to_owned(),
2252 network_generation_hash_seed: "BB".to_owned(),
2253 roles: 3,
2254 port: 7900,
2255 network_identifier: 0x98,
2256 host: String::new(),
2257 friendly_name: "heika".to_owned(),
2258 node_public_key: Some("CC".to_owned()),
2259 },
2260 peers: Vec::new(),
2261 chain: ChainInfoJson::new(10, 10, 1, 2, 8, "DD".to_owned()),
2262 unlocked: UnlockedAccountJson {
2263 unlocked_account: vec!["EE".to_owned()],
2264 },
2265 delegations: vec![DelegationJson {
2266 main_public_key: Some("FF".to_owned()),
2267 remote_public_key: "EE".to_owned(),
2268 height: Some("7".to_owned()),
2269 state: DelegationStateJson::Accepted,
2270 reason: None,
2271 }],
2272 }))
2273 }
2274
2275 async fn get(shared: Shared, path: &str) -> (Option<HeaderValue>, serde_json::Value) {
2276 let response = router(shared, node(submit(Arc::default())))
2277 .oneshot(Request::get(path).body(Body::empty()).unwrap())
2278 .await
2279 .unwrap();
2280 assert!(
2281 response.status().is_success(),
2282 "{path}: {}",
2283 response.status()
2284 );
2285 let origin = response.headers().get(ACCESS_CONTROL_ALLOW_ORIGIN).cloned();
2286 let body = response.into_body().collect().await.unwrap().to_bytes();
2287 (origin, serde_json::from_slice(&body).unwrap())
2288 }
2289
2290 #[tokio::test]
2291 async fn answers_from_the_snapshot_with_open_cors() {
2292 let shared = snapshot();
2293 let (origin, node) = get(Arc::clone(&shared), "/node/info").await;
2294 assert_eq!(origin, Some(HeaderValue::from_static("*")));
2295 assert_eq!(node["nodePublicKey"], "CC");
2296 let (_, chain) = get(Arc::clone(&shared), "/chain/info").await;
2297 assert_eq!(chain["latestFinalizedBlock"]["height"], "8");
2298 let (_, unlocked) = get(Arc::clone(&shared), "/node/unlockedaccount").await;
2299 assert_eq!(unlocked["unlockedAccount"][0], "EE");
2300 let (_, delegations) = get(Arc::clone(&shared), "/heika/delegations").await;
2301 assert_eq!(delegations[0]["state"], "accepted");
2302 let peer = NodeInfoJson {
2304 node_public_key: None,
2305 host: "peer.example".to_owned(),
2306 ..shared.read().unwrap().node.clone()
2307 };
2308 shared.write().unwrap().peers = vec![peer];
2309 let (_, peers) = get(Arc::clone(&shared), "/node/peers").await;
2310 assert_eq!(peers[0]["host"], "peer.example");
2311 assert!(peers[0].get("nodePublicKey").is_none());
2312 shared.write().unwrap().chain = ChainInfoJson::new(11, 11, 1, 3, 9, "DD".to_owned());
2314 let (_, chain) = get(shared, "/chain/info").await;
2315 assert_eq!(chain["height"], "11");
2316 }
2317
2318 struct FakeReader;
2320
2321 static LAST_FILTER: std::sync::Mutex<Option<TransactionFilter>> = std::sync::Mutex::new(None);
2323
2324 const CURRENCY: u64 = 0x6BED_913F_A202_23F8;
2325
2326 fn known() -> Address {
2327 Address::from_public_key(&PublicKey([0x11; 32]), NetworkIdentifier::TESTNET)
2328 }
2329
2330 fn metadata_composite() -> Hash256 {
2332 heika_transaction::MetadataKey {
2333 source_address: known(),
2334 target_address: known(),
2335 scoped_metadata_key: 1,
2336 target_id: 0,
2337 metadata_type: heika_transaction::MetadataType::Account,
2338 }
2339 .unique_key()
2340 }
2341
2342 fn fake_multisig_address(name: char) -> Address {
2345 Address::from_public_key(&PublicKey([name as u8; 32]), NetworkIdentifier::TESTNET)
2346 }
2347
2348 fn fake_multisigs() -> Vec<MultisigJson> {
2349 let entry = |address: Address, cosignatories: &[Address], multisigs: &[Address]| {
2350 let hexes = |addresses: &[Address]| addresses.iter().map(Address::to_hex).collect();
2351 MultisigJson {
2352 version: 1,
2353 account_address: address.to_hex(),
2354 min_approval: cosignatories.len() as u32,
2355 min_removal: 1,
2356 cosignatory_addresses: hexes(cosignatories),
2357 multisig_addresses: hexes(multisigs),
2358 }
2359 };
2360 let [u, m, c] = ['U', 'M', 'C'].map(fake_multisig_address);
2361 vec![
2362 entry(u, &[m], &[]),
2363 entry(m, &[known(), c], &[u]),
2364 entry(known(), &[], &[m]),
2365 entry(c, &[], &[m]),
2366 ]
2367 }
2368
2369 fn check_at(at: Option<u64>) -> Result<(), StateError> {
2370 match at {
2371 Some(height) if height > 10 => Err(StateError::Ahead { height, tip: 10 }),
2372 Some(height) if height < 5 => Err(StateError::NoHistory { height }),
2373 _ => Ok(()),
2374 }
2375 }
2376
2377 impl Reader for FakeReader {
2378 fn accounts(
2379 &self,
2380 addresses: &[Address],
2381 at: Option<u64>,
2382 ) -> Result<Vec<AccountJson>, StateError> {
2383 check_at(at)?;
2384 let account = |address: &Address| {
2385 let mut bytes = vec![1, 0];
2386 bytes.extend_from_slice(&address.0);
2387 bytes.extend_from_slice(&1u64.to_le_bytes());
2388 bytes.extend_from_slice(&[0x11; 32]);
2389 bytes.extend_from_slice(&2u64.to_le_bytes());
2390 bytes.extend_from_slice(&[0, 0, 0, 0, 0, 0]);
2391 AccountJson::from_state_bytes(&bytes).unwrap()
2392 };
2393 Ok(addresses
2394 .iter()
2395 .filter(|address| **address == known())
2396 .map(account)
2397 .collect())
2398 }
2399
2400 fn mosaics(
2401 &self,
2402 ids: &[u64],
2403 at: Option<u64>,
2404 ) -> Result<Vec<MosaicStateJson>, StateError> {
2405 check_at(at)?;
2406 let mosaic = |id: &u64| {
2407 let mut bytes = vec![1, 0];
2408 bytes.extend_from_slice(&id.to_le_bytes());
2409 bytes.extend_from_slice(&[0; 54]);
2410 MosaicStateJson::from_state_bytes(&bytes).unwrap()
2411 };
2412 Ok(ids
2413 .iter()
2414 .filter(|id| **id == CURRENCY)
2415 .map(mosaic)
2416 .collect())
2417 }
2418
2419 fn multisigs(
2420 &self,
2421 addresses: &[Address],
2422 at: Option<u64>,
2423 ) -> Result<Vec<MultisigJson>, StateError> {
2424 check_at(at)?;
2425 Ok(addresses
2426 .iter()
2427 .filter_map(|address| {
2428 fake_multisigs()
2429 .into_iter()
2430 .find(|entry| entry.account_address == address.to_hex())
2431 })
2432 .collect())
2433 }
2434
2435 fn multisig_graph(
2436 &self,
2437 address: &Address,
2438 at: Option<u64>,
2439 ) -> Result<Option<Vec<MultisigGraphLevel>>, StateError> {
2440 multisig_graph(address, |addresses| self.multisigs(addresses, at))
2441 }
2442
2443 fn lock_or_restriction_states(
2445 &self,
2446 cache: SubCache,
2447 keys: &[Vec<u8>],
2448 at: Option<u64>,
2449 ) -> Result<KeyedStates, StateError> {
2450 check_at(at)?;
2451 let state = |key: &[u8]| match cache {
2452 SubCache::HashLockInfo if key == [0x44; 32] => Some(
2453 HashLockJson {
2454 version: 1,
2455 owner_address: known().to_hex(),
2456 mosaic_id: format!("{CURRENCY:016X}"),
2457 amount: "10000000".to_owned(),
2458 end_height: "480".to_owned(),
2459 status: 0,
2460 hash: "44".repeat(32),
2461 }
2462 .to_state_bytes()
2463 .unwrap(),
2464 ),
2465 SubCache::AccountRestriction if key == known().0 => Some(
2466 AccountRestrictionsJson {
2467 version: 1,
2468 address: known().to_hex(),
2469 restrictions: vec![heika_rest::state::AccountRestrictionJson {
2470 restriction_flags: 0xC004,
2471 values: vec![heika_rest::state::AccountRestrictionValue::Operation(
2472 0x4154,
2473 )],
2474 }],
2475 }
2476 .to_state_bytes()
2477 .unwrap(),
2478 ),
2479 _ => None,
2480 };
2481 Ok(keys
2482 .iter()
2483 .filter_map(|key| state(key).map(|bytes| (key.clone(), bytes)))
2484 .collect())
2485 }
2486
2487 fn namespace(&self, id: u64, at: Option<u64>) -> Result<Option<NamespaceInfo>, StateError> {
2488 check_at(at)?;
2489 let mut bytes = vec![1, 0];
2491 bytes.extend_from_slice(&0xA1u64.to_le_bytes());
2492 bytes.extend_from_slice(&[0x68; 24]);
2493 bytes.extend_from_slice(&1u64.to_le_bytes());
2494 bytes.extend_from_slice(&u64::MAX.to_le_bytes());
2495 bytes.push(0);
2496 bytes.extend_from_slice(&1u64.to_le_bytes());
2497 bytes.push(1);
2498 bytes.extend_from_slice(&0xB2u64.to_le_bytes());
2499 bytes.push(0);
2500 let state = heika_rest::state::RootNamespaceState::from_state_bytes(&bytes).unwrap();
2501 Ok(state.info(id, at.unwrap_or(10)).unwrap())
2502 }
2503
2504 fn metadata(
2505 &self,
2506 composite_hash: &Hash256,
2507 at: Option<u64>,
2508 ) -> Result<Option<MetadataEntryJson>, StateError> {
2509 check_at(at)?;
2510 if *composite_hash != metadata_composite() {
2511 return Ok(None);
2512 }
2513 let mut bytes = vec![1, 0];
2514 bytes.extend_from_slice(&known().0);
2515 bytes.extend_from_slice(&known().0);
2516 bytes.extend_from_slice(&1u64.to_le_bytes());
2517 bytes.extend_from_slice(&0u64.to_le_bytes());
2518 bytes.push(0);
2519 bytes.extend_from_slice(&2u16.to_le_bytes());
2520 bytes.extend_from_slice(b"hi");
2521 Ok(Some(MetadataEntryJson::from_state_bytes(&bytes).unwrap()))
2522 }
2523
2524 fn search_metadata(
2525 &self,
2526 filter: &MetadataFilter,
2527 page: PageRequest,
2528 after: Option<&MetadataPosition>,
2529 at: Option<u64>,
2530 ) -> Result<Option<Vec<MetadataEntryJson>>, StateError> {
2531 check_at(at)?;
2532 if filter.target_id == Some(0xDEAD) || at == Some(6) {
2534 return Ok(None);
2535 }
2536 let count = match filter.source {
2539 Some(source) if source == known() => 1,
2540 Some(_) => 0,
2541 None => page.size,
2542 };
2543 let entry = self.metadata(&metadata_composite(), None).unwrap().unwrap();
2544 let value = format!(
2546 "{}{}{}{}",
2547 page.number,
2548 if page.descending { "d" } else { "" },
2549 at.map(|height| format!("@{height}")).unwrap_or_default(),
2550 after
2551 .map(|after| format!("+{:X}", after.scoped_key))
2552 .unwrap_or_default()
2553 );
2554 Ok(Some(vec![
2555 MetadataEntryJson {
2556 value: value.clone(),
2557 ..entry
2558 };
2559 count
2560 ]))
2561 }
2562
2563 fn search_namespaces(
2564 &self,
2565 filter: &NamespaceFilter,
2566 page: PageRequest,
2567 after: Option<&[u8]>,
2568 at: Option<u64>,
2569 ) -> Result<Option<Vec<(String, NamespaceInfo)>>, StateError> {
2570 check_at(at)?;
2571 if filter.alias_type == Some(9) {
2573 return Ok(None);
2574 }
2575 if after.is_some_and(|after| after[0] != 4) {
2577 return Err(StateError::Invalid(
2578 "offset is not of this search".to_owned(),
2579 ));
2580 }
2581 let _ = page;
2582 Ok(Some(
2583 [0xA1, 0xB2]
2584 .into_iter()
2585 .filter(|&id| {
2586 filter
2587 .registration_type
2588 .is_none_or(|kind| kind == u8::from(id != 0xA1))
2589 })
2590 .map(|id| {
2591 let info = self.namespace(id, at).unwrap().unwrap();
2592 (format!("04{id:02X}"), info)
2593 })
2594 .collect(),
2595 ))
2596 }
2597
2598 fn namespace_names(&self, ids: &[u64]) -> Result<Option<Vec<NamespaceNameJson>>, String> {
2599 let mut out = Vec::new();
2601 for &id in ids {
2602 if id == 0xB2 {
2603 out.push(NamespaceNameJson {
2604 id: "00000000000000B2".to_owned(),
2605 name: "xym".to_owned(),
2606 parent_id: Some("00000000000000A1".to_owned()),
2607 });
2608 }
2609 if id == 0xA1 || id == 0xB2 {
2610 out.push(NamespaceNameJson {
2611 id: "00000000000000A1".to_owned(),
2612 name: "hina".to_owned(),
2613 parent_id: None,
2614 });
2615 }
2616 }
2617 Ok(Some(out))
2618 }
2619
2620 fn alias_names(&self, target: AliasTarget) -> Result<Option<Vec<String>>, String> {
2621 Ok(match target {
2622 AliasTarget::Address(address) if address == known() => {
2623 Some(vec!["hina.xym".to_owned()])
2624 }
2625 AliasTarget::Mosaic(0xDEAD) => None,
2627 AliasTarget::Mosaic(CURRENCY) => Some(vec!["symbol.xym".to_owned()]),
2628 _ => Some(Vec::new()),
2629 })
2630 }
2631
2632 fn state_path(
2633 &self,
2634 cache: SubCache,
2635 key: &Hash256,
2636 at: Option<u64>,
2637 ) -> Result<MerkleStateInfo, StateError> {
2638 check_at(at)?;
2639 let height = at.map(|height| format!("@{height}")).unwrap_or_default();
2641 Ok(MerkleStateInfo {
2642 raw: format!("{:02X}{key}{height}", cache.index()),
2643 })
2644 }
2645
2646 fn block(&self, height: u64) -> Result<Option<BlockInfo>, String> {
2648 if !(1..=10).contains(&height) || height == 5 {
2649 return Ok(None);
2650 }
2651 Ok(Some(
2652 serde_json::from_value(serde_json::json!({
2653 "meta": {
2654 "hash": "00", "generationHash": "00", "totalFee": "0",
2655 "stateHashSubCacheMerkleRoots": [], "totalTransactionsCount": 0,
2656 "transactionsCount": 0, "statementsCount": 0,
2657 },
2658 "block": {
2659 "size": 376, "signature": "00", "signerPublicKey": "00", "version": 1,
2660 "network": 152, "type": 33091, "height": height.to_string(), "timestamp": "0",
2661 "difficulty": "0", "proofGamma": "00", "proofVerificationHash": "00",
2662 "proofScalar": "00", "previousBlockHash": "00", "transactionsHash": "00",
2663 "receiptsHash": "00", "stateHash": "00", "beneficiaryAddress": "00",
2664 "feeMultiplier": 0,
2665 },
2666 }))
2667 .unwrap(),
2668 ))
2669 }
2670
2671 fn finalization_proof(&self, epoch: u32) -> Result<Option<Vec<u8>>, String> {
2672 let proof = || {
2674 serde_json::from_value::<FinalizationProof>(serde_json::json!({
2675 "version": 1, "finalizationEpoch": 3, "finalizationPoint": 2, "height": "120",
2676 "hash": "AB".repeat(32), "messageGroups": [],
2677 }))
2678 .unwrap()
2679 .to_bytes()
2680 .unwrap()
2681 };
2682 Ok(match epoch {
2683 3 => Some(proof()),
2684 4 => Some(vec![1, 2, 3]),
2685 _ => None,
2686 })
2687 }
2688
2689 fn transaction_status(&self, hash: &Hash256) -> Result<Option<TransactionStatus>, String> {
2690 Ok((hash.0 == [0xAA; 32]).then(|| TransactionStatus {
2691 group: "confirmed".to_owned(),
2692 code: Some("Success".to_owned()),
2693 hash: hash.to_string(),
2694 deadline: Some("1".to_owned()),
2695 height: Some("7".to_owned()),
2696 }))
2697 }
2698
2699 fn confirmed_transaction(
2700 &self,
2701 _hash: &Hash256,
2702 ) -> Result<Option<TransactionInfo>, String> {
2703 Ok(None)
2704 }
2705
2706 fn search_transactions(
2709 &self,
2710 filter: &TransactionFilter,
2711 page: PageRequest,
2712 after: Option<(u64, u32, u16)>,
2713 ) -> Result<Option<Vec<TransactionInfo>>, String> {
2714 let unkept =
2715 Address::from_public_key(&PublicKey([0x23; 32]), NetworkIdentifier::TESTNET);
2716 *LAST_FILTER.lock().unwrap() = Some(filter.clone());
2717 if filter.address == Some(unkept) {
2718 return Ok(None);
2719 }
2720 let mut heights: Vec<u64> = if filter.address.is_none_or(|address| address == known()) {
2722 (1..=25)
2723 .filter(|height| (filter.from_height..=filter.to_height).contains(height))
2724 .collect()
2725 } else {
2726 Vec::new()
2727 };
2728 if page.descending {
2729 heights.reverse();
2730 }
2731 if let Some((after, _, _)) = after {
2732 heights.retain(|&height| {
2733 if page.descending {
2734 height < after
2735 } else {
2736 height > after
2737 }
2738 });
2739 }
2740 let transaction = heika_transaction::Transaction::new(
2741 PublicKey([0x11; 32]),
2742 NetworkIdentifier::TESTNET,
2743 0,
2744 0,
2745 heika_transaction::Body::Transfer(
2746 heika_transaction::Transfer::new(
2747 known().into(),
2748 Default::default(),
2749 Vec::new(),
2750 )
2751 .unwrap(),
2752 ),
2753 );
2754 Ok(Some(
2755 heights
2756 .into_iter()
2757 .skip((page.number - 1) * page.size)
2758 .take(page.size)
2759 .map(|height| TransactionInfo {
2760 id: Some(heika_rest::transaction::transaction_position(height, 0, 0)),
2761 meta: heika_rest::transaction::TransactionMeta {
2762 height: Some(height.to_string()),
2763 hash: None,
2764 merkle_component_hash: None,
2765 index: Some(0),
2766 aggregate_hash: None,
2767 aggregate_id: None,
2768 timestamp: None,
2769 fee_multiplier: None,
2770 },
2771 transaction: heika_rest::transaction::TransactionJson::from(&transaction),
2772 })
2773 .collect(),
2774 ))
2775 }
2776
2777 fn transaction_merkle(
2778 &self,
2779 height: u64,
2780 hash: &Hash256,
2781 ) -> Result<Option<MerkleProofInfo>, String> {
2782 Ok(
2783 (height == 7 && hash.0 == [0xAA; 32]).then(|| MerkleProofInfo {
2784 merkle_path: Vec::new(),
2785 }),
2786 )
2787 }
2788
2789 fn partial_transaction(&self, _hash: &Hash256) -> Result<Option<TransactionInfo>, String> {
2790 Ok(None)
2791 }
2792
2793 fn unconfirmed_transaction(
2794 &self,
2795 hash: &Hash256,
2796 ) -> Result<Option<TransactionInfo>, String> {
2797 Ok((hash.0 == [0xAA; 32]).then(|| {
2798 serde_json::from_value(serde_json::json!({
2799 "meta": {"height": "0"},
2800 "transaction": {"signerPublicKey": "AA", "version": 1, "network": 152, "type": 16724}
2801 }))
2802 .unwrap()
2803 }))
2804 }
2805
2806 fn unconfirmed_transactions(
2807 &self,
2808 filter: &PartialFilter,
2809 embedded: bool,
2810 ) -> Result<Vec<TransactionInfo>, String> {
2811 let count = match (embedded, filter.address) {
2813 (true, _) => 12,
2814 (false, Some(_)) => 1,
2815 (false, None) => 2,
2816 };
2817 let info: TransactionInfo = serde_json::from_value(serde_json::json!({
2818 "meta": {"height": "0"},
2819 "transaction": {"signerPublicKey": "AA", "version": 1, "network": 152, "type": 16724}
2820 }))
2821 .unwrap();
2822 Ok(vec![info; count])
2823 }
2824
2825 fn partial_transactions(
2826 &self,
2827 filter: &PartialFilter,
2828 ) -> Result<Vec<TransactionInfo>, String> {
2829 let count = match (filter.signer, filter.address) {
2831 (Some(_), _) => 0,
2832 (None, Some(_)) => 25,
2833 (None, None) => 3,
2834 };
2835 let info: TransactionInfo = serde_json::from_value(serde_json::json!({
2836 "meta": {"height": "0"},
2837 "transaction": {"signerPublicKey": "AA", "version": 1, "network": 152, "type": 16961}
2838 }))
2839 .unwrap();
2840 Ok(vec![info; count])
2841 }
2842
2843 fn transaction_fees(&self) -> Result<TransactionFeesJson, String> {
2844 Ok(TransactionFeesJson::new(vec![10, 30], 10))
2845 }
2846
2847 fn network(&self) -> NetworkIdentifier {
2848 NetworkIdentifier::TESTNET
2849 }
2850 }
2851
2852 fn node(submit: Submit) -> Node {
2853 Node {
2854 submit_partial: Arc::clone(&submit),
2855 submit_cosignature: Arc::clone(&submit),
2856 submit_block: Arc::clone(&submit),
2857 submit,
2858 reader: Arc::new(FakeReader),
2859 network_properties: Arc::new(NetworkPropertiesJson::default()),
2860 epoch: testnet_epoch(),
2861 }
2862 }
2863
2864 async fn get_response(path: &str) -> Response {
2865 router(snapshot(), node(submit(Arc::default())))
2866 .oneshot(Request::get(path).body(Body::empty()).unwrap())
2867 .await
2868 .unwrap()
2869 }
2870
2871 async fn get_status(path: &str) -> (StatusCode, serde_json::Value) {
2872 let response = get_response(path).await;
2873 let status = response.status();
2874 let body = response.into_body().collect().await.unwrap().to_bytes();
2875 (status, serde_json::from_slice(&body).unwrap())
2876 }
2877
2878 #[tokio::test]
2879 async fn answers_network_server_and_health_like_catapult() {
2880 let (status, body) = get_status("/network").await;
2881 assert_eq!(status, StatusCode::OK);
2882 assert!(body["name"].is_string() && body["description"].is_string());
2883 let (status, body) = get_status("/network/properties").await;
2884 assert_eq!(status, StatusCode::OK);
2885 assert!(body["network"].is_object() && body["chain"].is_object());
2886 assert!(body["plugins"]["aggregate"].is_object());
2887 let (status, body) = get_status("/node/server").await;
2888 assert_eq!(status, StatusCode::OK);
2889 assert_eq!(body["serverInfo"]["restVersion"], env!("CARGO_PKG_VERSION"));
2890 assert_eq!(body["serverInfo"]["deployment"]["deploymentTool"], "heika");
2891 assert_eq!(body["serverInfo"]["deployment"]["lastUpdatedDate"], "N/A");
2892 let (status, body) = get_status("/node/health").await;
2893 assert_eq!(status, StatusCode::OK);
2894 assert_eq!(body["status"]["apiNode"], "up");
2895 assert_eq!(body["status"]["db"], "up");
2896 }
2897
2898 fn testnet_epoch() -> SystemTime {
2900 heika_core::network::NetworkParameters::TESTNET.epoch()
2901 }
2902
2903 #[tokio::test]
2904 async fn answers_node_time_in_network_milliseconds_like_catapult() {
2905 let before = network_millis(testnet_epoch(), SystemTime::now());
2906 let (status, body) = get_status("/node/time").await;
2907 let after = network_millis(testnet_epoch(), SystemTime::now());
2908 assert_eq!(status, StatusCode::OK);
2909 let timestamps = &body["communicationTimestamps"];
2910 let millis = |name: &str| timestamps[name].as_str().unwrap().parse::<u64>().unwrap();
2911 let (receive, send) = (millis("receiveTimestamp"), millis("sendTimestamp"));
2912 assert!(before <= receive && receive <= send && send <= after);
2913 }
2914
2915 #[test]
2916 fn network_millis_counts_from_the_epoch_and_never_goes_below_zero() {
2917 let later = testnet_epoch() + Duration::from_micros(1_500_999);
2918 assert_eq!(network_millis(testnet_epoch(), later), 1_500);
2919 let earlier = testnet_epoch() - Duration::from_secs(1);
2920 assert_eq!(network_millis(testnet_epoch(), earlier), 0);
2921 }
2922
2923 #[tokio::test]
2924 async fn returns_the_offered_source() {
2925 let (status, body) = get_status("/heika/sourcecode.zip").await;
2927 assert_eq!(status, StatusCode::NOT_FOUND);
2928 assert_eq!(body["code"], "ResourceNotFound");
2929 offer_source(b"PK\x05\x06");
2930 let response = router(snapshot(), node(submit(Arc::default())))
2931 .oneshot(
2932 Request::get("/heika/sourcecode.zip")
2933 .body(Body::empty())
2934 .unwrap(),
2935 )
2936 .await
2937 .unwrap();
2938 assert_eq!(response.status(), StatusCode::OK);
2939 assert_eq!(response.headers()[CONTENT_TYPE], "application/zip");
2940 let body = response.into_body().collect().await.unwrap().to_bytes();
2941 assert_eq!(&body[..], b"PK\x05\x06");
2942 }
2943
2944 #[tokio::test]
2945 async fn searches_metadata_like_catapult() {
2946 let source = known();
2947 let (status, body) = get_status(&format!("/metadata?sourceAddress={source}")).await;
2948 assert_eq!(status, StatusCode::OK);
2949 assert_eq!(body["data"].as_array().unwrap().len(), 1);
2950 assert_eq!(
2951 body["data"][0]["metadataEntry"]["compositeHash"],
2952 metadata_composite().to_string().as_str()
2953 );
2954 assert_eq!(body["pagination"]["pageNumber"], 1);
2955 assert_eq!(body["pagination"]["pageSize"], 10);
2956 let id = body["data"][0]["id"].as_str().unwrap().to_owned();
2958 let entry: MetadataEntryJson =
2959 serde_json::from_value(body["data"][0]["metadataEntry"].clone()).unwrap();
2960 assert_eq!(id, entry.position());
2961 let (status, body) = get_status(&format!("/metadata?offset={id}")).await;
2962 assert_eq!(status, StatusCode::OK);
2963 assert_eq!(body["data"][0]["metadataEntry"]["value"], "1+1");
2964 let (_, body) = get_status(&format!("/metadata/{}", metadata_composite())).await;
2966 assert_eq!(body["id"], id.as_str());
2967 let other = Address::from_public_key(&PublicKey([0x22; 32]), NetworkIdentifier::TESTNET);
2968 let (_, body) = get_status(&format!("/metadata?sourceAddress={}", other.to_hex())).await;
2969 assert!(body["data"].as_array().unwrap().is_empty());
2970
2971 let (_, body) =
2973 get_status("/metadata?pageSize=500&pageNumber=3&order=desc&metadataType=1").await;
2974 assert_eq!(body["data"].as_array().unwrap().len(), 100);
2975 assert_eq!(body["data"][0]["metadataEntry"]["value"], "3d");
2976 assert_eq!(body["pagination"]["pageSize"], 100);
2977
2978 for query in [
2980 "sourceAddress=zzz".to_owned(),
2981 format!("targetAddress={}", "11".repeat(32)),
2982 "scopedMetadataKey=12".to_owned(),
2983 "targetId=xyz".to_owned(),
2984 "order=up".to_owned(),
2985 "height=0".to_owned(),
2986 "height=11".to_owned(),
2987 "offset=6962CF6A2976BBB47C1054BC".to_owned(),
2988 format!("offset={}", "G".repeat(130)),
2989 ] {
2990 let (status, body) = get_status(&format!("/metadata?{query}")).await;
2991 assert_eq!(status, StatusCode::CONFLICT, "{query}");
2992 assert_eq!(body["code"], "InvalidArgument");
2993 }
2994
2995 for query in ["targetId=000000000000DEAD", "height=6"] {
2997 let (status, body) = get_status(&format!("/metadata?{query}")).await;
2998 assert_eq!(status, StatusCode::NOT_IMPLEMENTED, "{query}");
2999 assert_eq!(body["code"], "NotImplemented");
3000 }
3001
3002 let response = get_response("/metadata?height=7").await;
3004 assert_eq!(response.status(), StatusCode::OK);
3005 assert_eq!(response.headers()[HEIGHT_HEADER], "7");
3006 let body = response.into_body().collect().await.unwrap().to_bytes();
3007 let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
3008 assert_eq!(body["data"][0]["metadataEntry"]["value"], "1@7");
3009 assert_eq!(get_status("/metadata?height=4").await.0, StatusCode::GONE);
3010 }
3011
3012 async fn post(path: &str, body: &str) -> (StatusCode, serde_json::Value) {
3013 let response = router(snapshot(), node(submit(Arc::default())))
3014 .oneshot(
3015 Request::post(path)
3016 .header("Content-Type", "application/json")
3017 .body(Body::from(body.to_owned()))
3018 .unwrap(),
3019 )
3020 .await
3021 .unwrap();
3022 let status = response.status();
3023 let body = response.into_body().collect().await.unwrap().to_bytes();
3024 (status, serde_json::from_slice(&body).unwrap())
3025 }
3026
3027 #[tokio::test]
3028 async fn reads_accounts_and_mosaics_in_a_batch_like_catapult() {
3029 let other = Address::from_public_key(&PublicKey([0x22; 32]), NetworkIdentifier::TESTNET);
3030 let (status, body) = post(
3032 "/accounts",
3033 &format!(
3034 r#"{{"addresses": ["{}", "{other}", "{}"]}}"#,
3035 known(),
3036 known().to_hex()
3037 ),
3038 )
3039 .await;
3040 assert_eq!(status, StatusCode::OK);
3041 assert_eq!(body.as_array().unwrap().len(), 1);
3042 assert_eq!(body[0]["account"]["address"], known().to_hex().as_str());
3043 let (_, body) = post(
3045 "/accounts",
3046 &format!(r#"{{"publicKeys": "{}"}}"#, "11".repeat(32)),
3047 )
3048 .await;
3049 assert_eq!(body[0]["account"]["address"], known().to_hex().as_str());
3050 let (_, body) = post(
3051 "/mosaics",
3052 r#"{"mosaicIds": ["000000000000DEAD", "6BED913FA20223F8"]}"#,
3053 )
3054 .await;
3055 assert_eq!(body.as_array().unwrap().len(), 1);
3056 assert_eq!(body[0]["mosaic"]["id"], "6BED913FA20223F8");
3057 let (status, body) = post("/mosaics", r#"{"mosaicIds": []}"#).await;
3058 assert_eq!((status, body), (StatusCode::OK, serde_json::json!([])));
3059
3060 let many: Vec<String> = (0..=MAX_STATE_IDS).map(|id| format!("{id:016X}")).collect();
3061 for (path, body) in [
3062 (
3063 "/accounts",
3064 format!(
3065 r#"{{"addresses": ["{}"], "publicKeys": ["{}"]}}"#,
3066 known(),
3067 "11".repeat(32)
3068 ),
3069 ),
3070 ("/accounts", "{}".to_owned()),
3071 ("/accounts", r#"{"publicKeys": ["11"]}"#.to_owned()),
3072 ("/mosaics", r#"{"mosaicIds": ["12"]}"#.to_owned()),
3073 (
3074 "/mosaics",
3075 serde_json::json!({ "mosaicIds": many }).to_string(),
3076 ),
3077 ] {
3078 let (status, response) = post(path, &body).await;
3079 assert_eq!(status, StatusCode::CONFLICT, "{path} {body}");
3080 assert_eq!(response["code"], "InvalidArgument");
3081 }
3082 }
3083
3084 #[tokio::test]
3085 async fn reads_multisigs_and_their_graph_like_catapult() {
3086 let [u, m, c] = ['U', 'M', 'C'].map(fake_multisig_address);
3087 let (status, body) = get_status(&format!("/account/{m}/multisig")).await;
3088 assert_eq!(status, StatusCode::OK);
3089 assert_eq!(body["multisig"]["accountAddress"], m.to_hex().as_str());
3090 assert_eq!(body["multisig"]["minApproval"], 2);
3091 let levels = |body: &serde_json::Value| -> Vec<(i64, Vec<String>)> {
3092 body.as_array()
3093 .unwrap()
3094 .iter()
3095 .map(|level| {
3096 let entries = level["multisigEntries"].as_array().unwrap();
3097 (
3098 level["level"].as_i64().unwrap(),
3099 entries
3100 .iter()
3101 .map(|entry| {
3102 entry["multisig"]["accountAddress"]
3103 .as_str()
3104 .unwrap()
3105 .to_owned()
3106 })
3107 .collect(),
3108 )
3109 })
3110 .collect()
3111 };
3112 let (status, body) = get_status(&format!("/account/{m}/multisig/graph")).await;
3114 assert_eq!(status, StatusCode::OK);
3115 assert_eq!(
3116 levels(&body),
3117 vec![
3118 (-1, vec![u.to_hex()]),
3119 (0, vec![m.to_hex()]),
3120 (1, vec![known().to_hex(), c.to_hex()]),
3121 ]
3122 );
3123 let (_, body) = get_status(&format!("/account/{}/multisig/graph", known().to_hex())).await;
3124 assert_eq!(
3125 levels(&body),
3126 vec![
3127 (-2, vec![u.to_hex()]),
3128 (-1, vec![m.to_hex()]),
3129 (0, vec![known().to_hex()])
3130 ]
3131 );
3132 let other = fake_multisig_address('Z');
3133 for path in [
3134 format!("/account/{other}/multisig"),
3135 format!("/account/{other}/multisig/graph"),
3136 ] {
3137 assert_eq!(get_status(&path).await.0, StatusCode::NOT_FOUND, "{path}");
3138 }
3139 let key = "11".repeat(32);
3141 assert_eq!(
3142 get_status(&format!("/account/{key}/multisig")).await.0,
3143 StatusCode::CONFLICT
3144 );
3145 let response = get_response(&format!("/account/{m}/multisig/graph?height=7")).await;
3146 assert_eq!(response.status(), StatusCode::OK);
3147 assert_eq!(response.headers()[HEIGHT_HEADER], "7");
3148 assert_eq!(
3149 get_status(&format!("/account/{m}/multisig?height=4"))
3150 .await
3151 .0,
3152 StatusCode::GONE
3153 );
3154 }
3155
3156 #[tokio::test]
3157 async fn reads_locks_and_restrictions_like_catapult() {
3158 let lock = "44".repeat(32);
3159 let (status, body) = get_status(&format!("/lock/hash/{lock}")).await;
3160 assert_eq!(status, StatusCode::OK);
3161 assert_eq!(body["lock"]["hash"], lock.as_str());
3162 assert_eq!(body["lock"]["status"], 0);
3163 assert_eq!(body["lock"]["endHeight"], "480");
3164 let (status, body) = get_status(&format!("/restrictions/account/{}", known())).await;
3165 assert_eq!(status, StatusCode::OK);
3166 assert_eq!(
3167 body["accountRestrictions"]["restrictions"],
3168 serde_json::json!([{ "restrictionFlags": 0xC004, "values": [0x4154] }])
3169 );
3170 let (status, body) = post(
3172 "/lock/hash",
3173 &format!(r#"{{"hashes": ["{lock}", "{}"]}}"#, "45".repeat(32)),
3174 )
3175 .await;
3176 assert_eq!(status, StatusCode::OK);
3177 assert_eq!(body.as_array().unwrap().len(), 1);
3178 let (_, body) = post(
3179 "/restrictions/account",
3180 &format!(r#"{{"addresses": "{}"}}"#, known()),
3181 )
3182 .await;
3183 assert_eq!(
3184 body[0]["accountRestrictions"]["address"],
3185 known().to_hex().as_str()
3186 );
3187 let other = "45".repeat(32);
3188 for path in [
3189 format!("/lock/hash/{other}"),
3190 format!("/lock/secret/{other}"),
3191 format!("/restrictions/mosaic/{other}"),
3192 ] {
3193 assert_eq!(get_status(&path).await.0, StatusCode::NOT_FOUND, "{path}");
3194 }
3195 let (_, body) = post(
3196 "/lock/secret",
3197 &format!(r#"{{"compositeHashes": ["{other}"]}}"#),
3198 )
3199 .await;
3200 assert_eq!(body, serde_json::json!([]));
3201 for (path, body) in [
3202 ("/lock/hash", r#"{"hashes": ["12"]}"#.to_owned()),
3203 ("/lock/secret", r#"{"hashes": []}"#.to_owned()),
3204 (
3205 "/restrictions/account",
3206 r#"{"addresses": ["11"]}"#.to_owned(),
3207 ),
3208 ] {
3209 let (status, response) = post(path, &body).await;
3210 assert_eq!(status, StatusCode::CONFLICT, "{path} {body}");
3211 assert_eq!(response["code"], "InvalidArgument");
3212 }
3213 assert_eq!(get_status("/lock/hash/12").await.0, StatusCode::CONFLICT);
3214 let response = get_response(&format!("/lock/hash/{lock}?height=7")).await;
3215 assert_eq!(response.headers()[HEIGHT_HEADER], "7");
3216 assert_eq!(
3217 get_status(&format!("/restrictions/account/{}?height=4", known()))
3218 .await
3219 .0,
3220 StatusCode::GONE
3221 );
3222 assert_ne!(
3224 get_status(&format!("/lock/hash/{lock}/merkle")).await.0,
3225 StatusCode::NOT_FOUND
3226 );
3227 }
3228
3229 #[tokio::test]
3230 async fn searches_confirmed_transactions_by_address() {
3231 let heights = |body: &serde_json::Value| -> Vec<String> {
3232 body["data"]
3233 .as_array()
3234 .unwrap()
3235 .iter()
3236 .map(|info| info["meta"]["height"].as_str().unwrap().to_owned())
3237 .collect()
3238 };
3239 let address = known();
3240 let (status, body) =
3241 get_status(&format!("/transactions/confirmed?address={address}")).await;
3242 assert_eq!(status, StatusCode::OK);
3243 assert_eq!(
3244 heights(&body),
3245 (1..=10).map(|h| h.to_string()).collect::<Vec<_>>()
3246 );
3247 assert_eq!(
3248 body["pagination"],
3249 serde_json::json!({"pageNumber": 1, "pageSize": 10})
3250 );
3251 let last = body["data"][9]["id"].as_str().unwrap().to_owned();
3253 assert_eq!(last, format!("{:012X}{:08X}{:04X}", 10, 0, 0));
3254 let (_, body) = get_status(&format!(
3255 "/transactions/confirmed?address={address}&offset={last}"
3256 ))
3257 .await;
3258 assert_eq!(heights(&body)[0], "11");
3259 let (_, body) = get_status(&format!(
3260 "/transactions/confirmed?address={address}&order=desc&fromHeight=3&toHeight=20&pageNumber=2"
3261 ))
3262 .await;
3263 assert_eq!(
3264 heights(&body),
3265 (3..=10).rev().map(|h| h.to_string()).collect::<Vec<_>>()
3266 );
3267 let (_, body) = get_status(&format!(
3268 "/transactions/confirmed?address={address}&height=7"
3269 ))
3270 .await;
3271 assert_eq!(heights(&body), vec!["7"]);
3272 let other = Address::from_public_key(&PublicKey([0x22; 32]), NetworkIdentifier::TESTNET);
3273 let (status, body) = get_status(&format!("/transactions/confirmed?address={other}")).await;
3274 assert_eq!(
3275 (status, body["data"].clone()),
3276 (StatusCode::OK, serde_json::json!([]))
3277 );
3278
3279 let key = "11".repeat(32);
3281 let (status, _) = get_status(&format!(
3282 "/transactions/confirmed?signerPublicKey={key}&recipientAddress={other}&type=16724&type=16961\
3283 &transferMosaicId=6BED913FA20223F8&fromTransferAmount=5&toTransferAmount=9"
3284 ))
3285 .await;
3286 assert_eq!(status, StatusCode::OK);
3287 let filter = LAST_FILTER.lock().unwrap().clone().unwrap();
3288 assert_eq!(filter.address, None);
3289 assert_eq!(filter.signer, Some(PublicKey([0x11; 32])));
3290 assert_eq!(filter.recipient, Some(other.0));
3291 assert_eq!(filter.types, vec![0x4154, 0x4241]);
3292 assert_eq!(
3293 (filter.mosaic, filter.from_amount, filter.to_amount),
3294 (Some(CURRENCY), Some(5), Some(9))
3295 );
3296 assert!(!filter.embedded);
3297 for (embedded, expected) in [("true", true), ("false", false)] {
3298 let (status, _) =
3299 get_status(&format!("/transactions/confirmed?embedded={embedded}")).await;
3300 assert_eq!(status, StatusCode::OK);
3301 assert_eq!(
3302 LAST_FILTER.lock().unwrap().clone().unwrap().embedded,
3303 expected
3304 );
3305 }
3306 let (status, body) = get_status("/transactions/confirmed?height=3").await;
3308 assert_eq!(
3309 (status, heights(&body)),
3310 (StatusCode::OK, vec!["3".to_owned()])
3311 );
3312
3313 let unkept = Address::from_public_key(&PublicKey([0x23; 32]), NetworkIdentifier::TESTNET);
3315 let (status, body) = get_status(&format!("/transactions/confirmed?address={unkept}")).await;
3316 assert_eq!(status, StatusCode::NOT_IMPLEMENTED);
3317 assert_eq!(body["code"], "NotImplemented");
3318 for path in [
3319 format!("/transactions/confirmed?address={address}&signerPublicKey={key}"),
3320 format!("/transactions/confirmed?address={address}&recipientAddress={other}"),
3321 "/transactions/confirmed?fromTransferAmount=1".to_owned(),
3322 "/transactions/confirmed?address=zzz".to_owned(),
3323 "/transactions/confirmed?signerPublicKey=11".to_owned(),
3324 "/transactions/confirmed?type=x".to_owned(),
3325 "/transactions/confirmed?embedded=yes".to_owned(),
3326 "/transactions/confirmed?transferMosaicId=12".to_owned(),
3327 format!("/transactions/confirmed?address={address}&offset=12"),
3328 format!("/transactions/confirmed?address={address}&fromHeight=x"),
3329 format!("/transactions/confirmed?address={address}&order=up"),
3330 ] {
3331 let (status, body) = get_status(&path).await;
3332 assert_eq!(status, StatusCode::CONFLICT, "{path}");
3333 assert_eq!(body["code"], "InvalidArgument");
3334 }
3335 }
3336
3337 #[tokio::test]
3338 async fn reads_a_batch_at_a_past_height() {
3339 let response = router(snapshot(), node(submit(Arc::default())))
3340 .oneshot(
3341 Request::post("/mosaics?height=7")
3342 .header("Content-Type", "application/json")
3343 .body(Body::from(r#"{"mosaicIds": ["6BED913FA20223F8"]}"#))
3344 .unwrap(),
3345 )
3346 .await
3347 .unwrap();
3348 assert_eq!(response.status(), StatusCode::OK);
3349 assert_eq!(response.headers()[HEIGHT_HEADER], "7");
3350 for (height, status) in [(4, StatusCode::GONE), (11, StatusCode::CONFLICT)] {
3351 let (got, _) = post(
3352 &format!("/accounts?height={height}"),
3353 &format!(r#"{{"addresses": ["{}"]}}"#, known()),
3354 )
3355 .await;
3356 assert_eq!(got, status, "{height}");
3357 }
3358 }
3359
3360 #[tokio::test]
3361 async fn searches_namespaces_and_their_names_like_catapult() {
3362 let (status, body) = get_status("/namespaces").await;
3363 assert_eq!(status, StatusCode::OK);
3364 assert_eq!(body["data"].as_array().unwrap().len(), 2);
3365 assert_eq!(body["data"][0]["id"], "04A1");
3366 assert_eq!(body["data"][1]["namespace"]["parentId"], "00000000000000A1");
3367 let (_, body) = get_status(&format!(
3368 "/namespaces?registrationType=1&ownerAddress={}&level0=00000000000000A1",
3369 known()
3370 ))
3371 .await;
3372 assert_eq!(body["data"].as_array().unwrap().len(), 1);
3373 assert_eq!(
3374 get_status("/namespaces?offset=04A1").await.0,
3375 StatusCode::OK
3376 );
3377
3378 for query in [
3380 "ownerAddress=zzz",
3381 "level0=A1",
3382 "offset=zz",
3383 "offset=05A1",
3384 "order=up",
3385 "height=0",
3386 ] {
3387 let (status, body) = get_status(&format!("/namespaces?{query}")).await;
3388 assert_eq!(status, StatusCode::CONFLICT, "{query}");
3389 assert_eq!(body["code"], "InvalidArgument");
3390 }
3391 assert_eq!(
3392 get_status("/namespaces?aliasType=9").await.0,
3393 StatusCode::NOT_IMPLEMENTED
3394 );
3395 let response = get_response("/namespaces?height=7").await;
3396 assert_eq!(response.headers()[HEIGHT_HEADER], "7");
3397 assert_eq!(get_status("/namespaces?height=4").await.0, StatusCode::GONE);
3398
3399 let (status, body) = post(
3401 "/namespaces/names",
3402 r#"{"namespaceIds": ["00000000000000B2"]}"#,
3403 )
3404 .await;
3405 assert_eq!(status, StatusCode::OK);
3406 assert_eq!(
3407 body,
3408 serde_json::json!([
3409 {"id": "00000000000000B2", "name": "xym", "parentId": "00000000000000A1"},
3410 {"id": "00000000000000A1", "name": "hina"}
3411 ])
3412 );
3413 let (status, body) = post(
3414 "/namespaces/account/names",
3415 &format!(
3416 r#"{{"addresses": ["{}", "{}"]}}"#,
3417 known(),
3418 Address::from_public_key(&PublicKey([0x22; 32]), NetworkIdentifier::TESTNET)
3419 .to_hex()
3420 ),
3421 )
3422 .await;
3423 assert_eq!(status, StatusCode::OK);
3424 assert_eq!(
3425 body["accountNames"][0]["address"],
3426 known().to_hex().as_str()
3427 );
3428 assert_eq!(
3429 body["accountNames"][0]["names"],
3430 serde_json::json!(["hina.xym"])
3431 );
3432 assert_eq!(body["accountNames"][1]["names"], serde_json::json!([]));
3433 let (_, body) = post(
3434 "/namespaces/mosaic/names",
3435 r#"{"mosaicIds": ["6BED913FA20223F8"]}"#,
3436 )
3437 .await;
3438 assert_eq!(
3439 body,
3440 serde_json::json!({"mosaicNames": [{"mosaicId": "6BED913FA20223F8", "names": ["symbol.xym"]}]})
3441 );
3442
3443 let many: Vec<String> = (0..101).map(|id| format!("{id:016X}")).collect();
3445 for (path, body) in [
3446 ("/namespaces/names", "{}".to_owned()),
3447 (
3448 "/namespaces/names",
3449 serde_json::json!({ "namespaceIds": many }).to_string(),
3450 ),
3451 (
3452 "/namespaces/account/names",
3453 r#"{"addresses": ["zzz"]}"#.to_owned(),
3454 ),
3455 (
3456 "/namespaces/mosaic/names",
3457 r#"{"mosaicIds": ["12"]}"#.to_owned(),
3458 ),
3459 ] {
3460 let (status, response) = post(path, &body).await;
3461 assert_eq!(status, StatusCode::CONFLICT, "{path} {body}");
3462 assert_eq!(response["code"], "InvalidArgument");
3463 }
3464 let (status, body) = post(
3465 "/namespaces/mosaic/names",
3466 r#"{"mosaicIds": ["000000000000DEAD"]}"#,
3467 )
3468 .await;
3469 assert_eq!(status, StatusCode::NOT_IMPLEMENTED);
3470 assert_eq!(body["code"], "NotImplemented");
3471 }
3472
3473 #[tokio::test]
3474 async fn reads_states_at_a_height() {
3475 let response = get_response("/mosaics/6BED913FA20223F8?height=7").await;
3477 assert_eq!(response.status(), StatusCode::OK);
3478 assert_eq!(response.headers()[HEIGHT_HEADER], "7");
3479 let response = get_response("/mosaics/6BED913FA20223F8").await;
3480 assert!(response.headers().get(HEIGHT_HEADER).is_none());
3481 let response = get_response("/mosaics/0000000000000001?height=7").await;
3483 assert_eq!(response.status(), StatusCode::NOT_FOUND);
3484 assert_eq!(response.headers()[HEIGHT_HEADER], "7");
3485
3486 let address = known();
3487 for path in [
3488 format!("/accounts/{address}"),
3489 "/mosaics/6BED913FA20223F8".to_owned(),
3490 "/namespaces/00000000000000A1".to_owned(),
3491 format!("/accounts/{address}/merkle"),
3492 "/namespaces/00000000000000B2/merkle".to_owned(),
3493 ] {
3494 assert_eq!(
3495 get_status(&format!("{path}?height=5")).await.0,
3496 StatusCode::OK,
3497 "{path}"
3498 );
3499 for height in ["11", "0", "x", "-1"] {
3501 let (status, body) = get_status(&format!("{path}?height={height}")).await;
3502 assert_eq!(status, StatusCode::CONFLICT, "{path} {height}");
3503 assert_eq!(body["code"], "InvalidArgument");
3504 }
3505 let (status, body) = get_status(&format!("{path}?height=4")).await;
3506 assert_eq!(status, StatusCode::GONE, "{path}");
3507 assert_eq!(body["code"], "Gone");
3508 }
3509
3510 let (_, body) = get_status("/mosaics/6BED913FA20223F8/merkle?height=6").await;
3512 assert!(body["raw"].as_str().unwrap().ends_with("@6"));
3513 let composite = metadata_composite();
3514 assert_eq!(
3515 get_status(&format!("/metadata/{composite}?height=6"))
3516 .await
3517 .0,
3518 StatusCode::OK
3519 );
3520 assert_eq!(
3521 get_status(&format!("/metadata/{composite}/merkle?height=4"))
3522 .await
3523 .0,
3524 StatusCode::GONE
3525 );
3526 }
3527
3528 #[tokio::test]
3529 async fn reads_accounts_mosaics_and_blocks() {
3530 let address = known();
3531 let hex_address = address.to_hex();
3532 for id in [address.to_string(), hex_address.clone(), "11".repeat(32)] {
3534 let (status, body) = get_status(&format!("/accounts/{id}")).await;
3535 assert_eq!(status, StatusCode::OK, "{id}");
3536 assert_eq!(body["account"]["address"], hex_address.as_str());
3537 }
3538 let other = Address::from_public_key(&PublicKey([0x22; 32]), NetworkIdentifier::TESTNET);
3539 let (status, body) = get_status(&format!("/accounts/{other}")).await;
3540 assert_eq!(status, StatusCode::NOT_FOUND);
3541 assert_eq!(body["code"], "ResourceNotFound");
3542 let mainnet = Address::from_public_key(&PublicKey([0x11; 32]), NetworkIdentifier::MAINNET);
3544 for id in ["zzz".to_owned(), mainnet.to_string()] {
3545 let (status, body) = get_status(&format!("/accounts/{id}")).await;
3546 assert_eq!(status, StatusCode::CONFLICT, "{id}");
3547 assert_eq!(body["code"], "InvalidArgument");
3548 }
3549 let (status, body) = get_status(&format!("/accounts/{address}/merkle")).await;
3550 assert_eq!(status, StatusCode::OK);
3551 assert_eq!(
3552 body["raw"],
3553 format!("00{}", patricia::address_key(&address)).as_str()
3554 );
3555
3556 let (status, body) = get_status("/mosaics/6BED913FA20223F8").await;
3557 assert_eq!(status, StatusCode::OK);
3558 assert_eq!(body["mosaic"]["id"], "6BED913FA20223F8");
3559 assert_eq!(
3560 get_status("/mosaics/0000000000000001").await.0,
3561 StatusCode::NOT_FOUND
3562 );
3563 assert_eq!(get_status("/mosaics/6BED").await.0, StatusCode::CONFLICT);
3564 let (_, body) = get_status("/mosaics/6BED913FA20223F8/merkle").await;
3565 assert_eq!(
3566 body["raw"],
3567 format!(
3568 "{:02X}{}",
3569 SubCache::Mosaic.index(),
3570 patricia::id_key(CURRENCY)
3571 )
3572 .as_str()
3573 );
3574
3575 let (status, body) = get_status("/namespaces/00000000000000A1").await;
3577 assert_eq!(status, StatusCode::OK);
3578 assert_eq!(body["meta"]["active"], true);
3579 assert_eq!(body["namespace"]["registrationType"], 0);
3580 let (status, body) = get_status("/namespaces/00000000000000B2").await;
3581 assert_eq!(status, StatusCode::OK);
3582 assert_eq!(body["namespace"]["level1"], "00000000000000B2");
3583 assert_eq!(body["namespace"]["parentId"], "00000000000000A1");
3584 assert_eq!(
3585 get_status("/namespaces/00000000000000C3").await.0,
3586 StatusCode::NOT_FOUND
3587 );
3588 assert_eq!(get_status("/namespaces/A1").await.0, StatusCode::CONFLICT);
3589 let (_, body) = get_status("/namespaces/00000000000000A1/merkle").await;
3590 assert_eq!(
3591 body["raw"],
3592 format!(
3593 "{:02X}{}",
3594 SubCache::Namespace.index(),
3595 patricia::id_key(0xA1)
3596 )
3597 .as_str()
3598 );
3599
3600 let composite = metadata_composite();
3602 let (status, body) = get_status(&format!("/metadata/{composite}")).await;
3603 assert_eq!(status, StatusCode::OK);
3604 assert_eq!(
3605 body["metadataEntry"]["compositeHash"],
3606 composite.to_string().as_str()
3607 );
3608 assert_eq!(body["metadataEntry"]["value"], "6869");
3609 assert_eq!(
3610 get_status(&format!("/metadata/{}", "00".repeat(32)))
3611 .await
3612 .0,
3613 StatusCode::NOT_FOUND
3614 );
3615 assert_eq!(get_status("/metadata/00").await.0, StatusCode::CONFLICT);
3616 let (_, body) = get_status(&format!("/metadata/{composite}/merkle")).await;
3617 assert_eq!(
3618 body["raw"],
3619 format!(
3620 "{:02X}{}",
3621 SubCache::Metadata.index(),
3622 patricia::hash_key(&composite)
3623 )
3624 .as_str()
3625 );
3626
3627 assert_eq!(get_status("/blocks/5").await.0, StatusCode::NOT_FOUND);
3628
3629 let (status, body) = get_status("/finalization/proof/epoch/3").await;
3631 assert_eq!(status, StatusCode::OK);
3632 assert_eq!(
3633 (
3634 &body["finalizationEpoch"],
3635 &body["finalizationPoint"],
3636 &body["height"]
3637 ),
3638 (&3.into(), &2.into(), &"120".into())
3639 );
3640 assert_eq!(body["messageGroups"], serde_json::json!([]));
3641 assert_eq!(
3642 get_status("/finalization/proof/epoch/5").await.0,
3643 StatusCode::NOT_FOUND
3644 );
3645 assert_eq!(
3646 get_status("/finalization/proof/epoch/4").await.0,
3647 StatusCode::INTERNAL_SERVER_ERROR
3648 );
3649 assert_eq!(
3650 get_status("/finalization/proof/epoch/-1").await.0,
3651 StatusCode::CONFLICT
3652 );
3653
3654 let heights = |body: &serde_json::Value| -> Vec<String> {
3656 body["data"]
3657 .as_array()
3658 .unwrap()
3659 .iter()
3660 .map(|block| block["block"]["height"].as_str().unwrap().to_owned())
3661 .collect()
3662 };
3663 let (status, body) = get_status("/blocks?orderBy=height&offset=3&pageSize=10").await;
3664 assert_eq!(status, StatusCode::OK);
3665 assert_eq!(heights(&body), ["4", "6", "7", "8", "9", "10"]);
3666 let (_, body) = get_status("/blocks").await;
3667 assert_eq!(heights(&body).len(), 9);
3668 let (_, body) = get_status("/blocks?order=desc&offset=8").await;
3669 assert_eq!(heights(&body), ["7", "6", "4", "3", "2", "1"]);
3670 let (_, body) = get_status("/blocks?order=desc").await;
3671 assert_eq!(heights(&body)[0], "10");
3672 let (_, body) = get_status("/blocks?pageNumber=2").await;
3673 assert!(heights(&body).is_empty());
3674 assert_eq!(
3675 get_status("/blocks?orderBy=size").await.0,
3676 StatusCode::CONFLICT
3677 );
3678 assert_eq!(
3679 get_status("/blocks?signerPublicKey=00").await.0,
3680 StatusCode::NOT_IMPLEMENTED
3681 );
3682
3683 let (status, body) = get_status("/transactions/partial").await;
3685 assert_eq!(status, StatusCode::OK);
3686 assert_eq!(body["data"].as_array().unwrap().len(), 3);
3687 assert_eq!(body["pagination"]["pageSize"], 10);
3688 let (_, body) = get_status(&format!(
3689 "/transactions/partial?address={}&pageSize=20&pageNumber=2",
3690 known()
3691 ))
3692 .await;
3693 assert_eq!(body["data"].as_array().unwrap().len(), 5);
3694 assert_eq!(body["pagination"]["pageNumber"], 2);
3695 let (_, body) = get_status(&format!(
3696 "/transactions/partial?signerPublicKey={}",
3697 "11".repeat(32)
3698 ))
3699 .await;
3700 assert!(body["data"].as_array().unwrap().is_empty());
3701 assert_eq!(
3702 get_status("/transactions/partial?address=zzz").await.0,
3703 StatusCode::CONFLICT
3704 );
3705 assert_eq!(
3706 get_status(&format!("/transactions/partial/{}", "AA".repeat(32)))
3707 .await
3708 .0,
3709 StatusCode::NOT_FOUND
3710 );
3711
3712 let (status, body) = get_status("/transactions/unconfirmed").await;
3714 assert_eq!(status, StatusCode::OK);
3715 assert_eq!(body["data"].as_array().unwrap().len(), 2);
3716 let (_, body) =
3717 get_status("/transactions/unconfirmed?embedded=true&pageSize=10&pageNumber=2").await;
3718 assert_eq!(body["data"].as_array().unwrap().len(), 2);
3719 let (_, body) = get_status(&format!("/transactions/unconfirmed?address={}", known())).await;
3720 assert_eq!(body["data"].as_array().unwrap().len(), 1);
3721 assert_eq!(
3722 get_status("/transactions/unconfirmed?embedded=yes").await.0,
3723 StatusCode::CONFLICT
3724 );
3725 let (status, body) =
3726 get_status(&format!("/transactions/unconfirmed/{}", "AA".repeat(32))).await;
3727 assert_eq!(status, StatusCode::OK);
3728 assert_eq!(body["transaction"]["type"], 16724);
3729 assert_eq!(
3730 get_status(&format!("/transactions/unconfirmed/{}", "BB".repeat(32)))
3731 .await
3732 .0,
3733 StatusCode::NOT_FOUND
3734 );
3735
3736 let (status, body) = get_status("/network/fees/transaction").await;
3737 assert_eq!(status, StatusCode::OK);
3738 assert_eq!(body["medianFeeMultiplier"], 20);
3739 assert_eq!(body["minFeeMultiplier"], 10);
3740
3741 let known = "AA".repeat(32);
3742 let (status, body) = get_status(&format!("/transactionStatus/{known}")).await;
3743 assert_eq!(status, StatusCode::OK);
3744 assert_eq!(body["group"], "confirmed");
3745 assert_eq!(body["height"], "7");
3746 let unknown = "BB".repeat(32);
3747 assert_eq!(
3748 get_status(&format!("/transactionStatus/{unknown}")).await.0,
3749 StatusCode::NOT_FOUND
3750 );
3751 assert_eq!(
3752 get_status("/transactionStatus/AB").await.0,
3753 StatusCode::CONFLICT
3754 );
3755 assert_eq!(
3756 get_status(&format!("/transactions/confirmed/{known}"))
3757 .await
3758 .0,
3759 StatusCode::NOT_FOUND
3760 );
3761 let (status, body) = get_status(&format!("/blocks/7/transactions/{known}/merkle")).await;
3762 assert_eq!(status, StatusCode::OK);
3763 assert_eq!(body["merklePath"], serde_json::json!([]));
3764 assert_eq!(
3765 get_status(&format!("/blocks/8/transactions/{known}/merkle"))
3766 .await
3767 .0,
3768 StatusCode::NOT_FOUND
3769 );
3770 for height in ["0", "abc"] {
3771 assert_eq!(
3772 get_status(&format!("/blocks/{height}")).await.0,
3773 StatusCode::CONFLICT
3774 );
3775 }
3776 }
3777
3778 fn submit(received: Arc<std::sync::Mutex<Vec<Vec<u8>>>>) -> Submit {
3780 Arc::new(move |bytes: Vec<u8>| {
3781 received.lock().unwrap().push(bytes.clone());
3782 if bytes == [1, 2] {
3783 Ok(())
3784 } else {
3785 Err("確かめが通りません".to_owned())
3786 }
3787 })
3788 }
3789
3790 async fn put(
3791 received: &Arc<std::sync::Mutex<Vec<Vec<u8>>>>,
3792 body: &str,
3793 ) -> (StatusCode, serde_json::Value) {
3794 put_to(received, "/transactions", body).await
3795 }
3796
3797 async fn put_to(
3798 received: &Arc<std::sync::Mutex<Vec<Vec<u8>>>>,
3799 path: &str,
3800 body: &str,
3801 ) -> (StatusCode, serde_json::Value) {
3802 let response = router(snapshot(), node(submit(Arc::clone(received))))
3803 .oneshot(
3804 Request::put(path)
3805 .header("Content-Type", "application/json")
3806 .body(Body::from(body.to_owned()))
3807 .unwrap(),
3808 )
3809 .await
3810 .unwrap();
3811 let status = response.status();
3812 let body = response.into_body().collect().await.unwrap().to_bytes();
3813 (status, serde_json::from_slice(&body).unwrap())
3814 }
3815
3816 #[tokio::test]
3817 async fn announces_transactions_like_catapult() {
3818 let received = Arc::default();
3819 let (status, answer) = put(&received, r#"{"payload":"0102"}"#).await;
3820 assert_eq!(status, StatusCode::ACCEPTED);
3821 assert_eq!(
3822 answer["message"],
3823 "packet 9 was pushed to the network via /transactions"
3824 );
3825 let (status, answer) = put(&received, r#"{"payload":"0a0B03"}"#).await;
3827 assert_eq!(status, StatusCode::CONFLICT);
3828 assert_eq!(answer["code"], "InvalidArgument");
3829 assert_eq!(answer["message"], "確かめが通りません");
3830 for payload in ["", "010", "01XY"] {
3832 let (status, _) = put(&received, &format!(r#"{{"payload":"{payload}"}}"#)).await;
3833 assert_eq!(status, StatusCode::CONFLICT, "{payload:?}");
3834 }
3835 assert_eq!(*received.lock().unwrap(), [vec![1, 2], vec![10, 11, 3]]);
3836 }
3837
3838 #[test]
3839 fn throttle_refills_up_to_one_second() {
3840 let start = Instant::now();
3841 let throttle = Throttle::new(3, start);
3842 assert!((0..3).all(|_| throttle.take(start)));
3843 assert!(!throttle.take(start));
3844 assert!(!throttle.take(start + Duration::from_millis(300)));
3846 assert!(throttle.take(start + Duration::from_millis(340)));
3847 let later = start + Duration::from_secs(10);
3849 assert!((0..3).all(|_| throttle.take(later)));
3850 assert!(!throttle.take(later));
3851 }
3852
3853 #[tokio::test]
3854 async fn answers_429_with_cors_over_the_limit() {
3855 let app = limit(router(snapshot(), node(submit(Arc::default()))), 1);
3856 let request = || Request::get("/chain/info").body(Body::empty()).unwrap();
3857 let first = app.clone().oneshot(request()).await.unwrap();
3858 assert_eq!(first.status(), StatusCode::OK);
3859 let second = app.oneshot(request()).await.unwrap();
3860 assert_eq!(second.status(), StatusCode::TOO_MANY_REQUESTS);
3861 assert_eq!(second.headers()[ACCESS_CONTROL_ALLOW_ORIGIN], "*");
3862 }
3863
3864 #[tokio::test]
3865 async fn takes_blocks_like_transactions() {
3866 let received = Arc::default();
3867 let (status, answer) = put_to(&received, "/blocks", r#"{"payload":"0102"}"#).await;
3868 assert_eq!(status, StatusCode::ACCEPTED);
3869 assert_eq!(
3870 answer["message"],
3871 "packet 3 was pushed to the network via /blocks"
3872 );
3873 let (status, answer) = put_to(&received, "/blocks", r#"{"payload":"0a0B03"}"#).await;
3874 assert_eq!(status, StatusCode::CONFLICT);
3875 assert_eq!(answer["message"], "確かめが通りません");
3876 let (status, _) = put_to(&received, "/blocks", r#"{"payload":"01XY"}"#).await;
3877 assert_eq!(status, StatusCode::CONFLICT);
3878 assert_eq!(*received.lock().unwrap(), [vec![1, 2], vec![10, 11, 3]]);
3879 }
3880
3881 #[tokio::test]
3882 async fn takes_blocks_up_to_the_p2p_size() {
3883 let received: Arc<std::sync::Mutex<Vec<Vec<u8>>>> = Arc::default();
3884 let put_body = |content_type: &'static str, body: Vec<u8>| {
3885 let app = router(snapshot(), node(submit(Arc::clone(&received))));
3886 async move {
3887 app.oneshot(
3888 Request::put("/blocks")
3889 .header("Content-Type", content_type)
3890 .body(Body::from(body))
3891 .unwrap(),
3892 )
3893 .await
3894 .unwrap()
3895 .status()
3896 }
3897 };
3898 let octets = "application/octet-stream";
3899 assert_eq!(
3901 put_body(octets, vec![0; MAX_BLOCK_BYTES]).await,
3902 StatusCode::CONFLICT
3903 );
3904 assert_eq!(
3905 put_body(octets, vec![0; MAX_BLOCK_BYTES + 1]).await,
3906 StatusCode::PAYLOAD_TOO_LARGE
3907 );
3908 let json = |size: usize| format!(r#"{{"payload":"{}"}}"#, "00".repeat(size)).into_bytes();
3909 assert_eq!(
3910 put_body("application/json", json(MAX_BLOCK_BYTES)).await,
3911 StatusCode::CONFLICT
3912 );
3913 assert_eq!(
3915 put_body("application/json", json(MAX_BLOCK_BYTES + 1)).await,
3916 StatusCode::PAYLOAD_TOO_LARGE
3917 );
3918 assert_eq!(
3919 put_body("application/json", json(MAX_BLOCK_BYTES + 1024)).await,
3920 StatusCode::PAYLOAD_TOO_LARGE
3921 );
3922 let sizes: Vec<usize> = received.lock().unwrap().iter().map(Vec::len).collect();
3923 assert_eq!(sizes, [MAX_BLOCK_BYTES, MAX_BLOCK_BYTES]);
3924 }
3925
3926 #[tokio::test]
3927 async fn takes_raw_blocks_as_octet_stream() {
3928 let received: Arc<std::sync::Mutex<Vec<Vec<u8>>>> = Arc::default();
3929 let put_raw = |content_type: &'static str, body: &'static [u8]| {
3930 let app = router(snapshot(), node(submit(Arc::clone(&received))));
3931 async move {
3932 app.oneshot(
3933 Request::put("/blocks")
3934 .header("Content-Type", content_type)
3935 .body(Body::from(body))
3936 .unwrap(),
3937 )
3938 .await
3939 .unwrap()
3940 .status()
3941 }
3942 };
3943 assert_eq!(
3944 put_raw("application/octet-stream", &[1, 2]).await,
3945 StatusCode::ACCEPTED
3946 );
3947 assert_eq!(
3949 put_raw("Application/Octet-Stream; charset=binary", &[1, 2]).await,
3950 StatusCode::ACCEPTED
3951 );
3952 assert_eq!(
3953 put_raw("application/octet-stream", &[10, 11, 3]).await,
3954 StatusCode::CONFLICT
3955 );
3956 assert!(put_raw("application/json", &[1, 2]).await.is_client_error());
3958 assert_eq!(
3960 put_raw("text/plain", br#"{"payload":"0102"}"#).await,
3961 StatusCode::UNSUPPORTED_MEDIA_TYPE
3962 );
3963 assert_eq!(
3964 *received.lock().unwrap(),
3965 [vec![1, 2], vec![1, 2], vec![10, 11, 3]]
3966 );
3967 }
3968
3969 #[tokio::test]
3970 async fn announces_partials_and_cosignatures_like_catapult() {
3971 let received = Arc::default();
3972 let (status, answer) =
3973 put_to(&received, "/transactions/partial", r#"{"payload":"0102"}"#).await;
3974 assert_eq!(status, StatusCode::ACCEPTED);
3975 assert_eq!(
3976 answer["message"],
3977 "packet 256 was pushed to the network via /transactions/partial"
3978 );
3979 let cosignature = format!(
3980 r#"{{"version":"0","signerPublicKey":"{}","signature":"{}","parentHash":"{}"}}"#,
3981 "11".repeat(32),
3982 "22".repeat(64),
3983 "33".repeat(32)
3984 );
3985 let (status, answer) = put_to(&received, "/transactions/cosignature", &cosignature).await;
3986 assert_eq!(status, StatusCode::CONFLICT, "{answer}");
3988 let passed = received.lock().unwrap().last().cloned().unwrap();
3989 assert_eq!(passed.len(), 136);
3990 assert_eq!(&passed[..8], &[0; 8]);
3991 assert_eq!(&passed[8..40], &[0x11; 32]);
3992 assert_eq!(&passed[104..], &[0x33; 32]);
3993 let before = received.lock().unwrap().len();
3995 let broken = cosignature.replace(&"33".repeat(32), "33");
3996 assert_eq!(
3997 put_to(&received, "/transactions/cosignature", &broken)
3998 .await
3999 .0,
4000 StatusCode::CONFLICT
4001 );
4002 let other_version = cosignature.replace(r#""version":"0""#, r#""version":"1""#);
4003 assert_eq!(
4004 put_to(&received, "/transactions/cosignature", &other_version)
4005 .await
4006 .0,
4007 StatusCode::CONFLICT
4008 );
4009 assert_eq!(received.lock().unwrap().len(), before);
4010 }
4011
4012 #[tokio::test]
4013 async fn answers_the_preflight_for_put() {
4014 let response = router(snapshot(), node(submit(Arc::default())))
4015 .oneshot(
4016 Request::options("/transactions")
4017 .body(Body::empty())
4018 .unwrap(),
4019 )
4020 .await
4021 .unwrap();
4022 assert!(response.status().is_success());
4023 let headers = response.headers();
4024 assert_eq!(headers[ACCESS_CONTROL_ALLOW_ORIGIN], "*");
4025 assert!(
4026 headers[ACCESS_CONTROL_ALLOW_METHODS]
4027 .to_str()
4028 .unwrap()
4029 .contains("PUT")
4030 );
4031 assert_eq!(headers[ACCESS_CONTROL_ALLOW_HEADERS], "Content-Type");
4032 }
4033}