Skip to main content

heika_packet/
lib.rs

1//! Symbol のノードどうしがやりとりするパケットの形。catapult の `ionet/Packet.h`、`ionet/NetworkNode.h`、
2//! `api/ChainPackets.h`、`handlers/ChainHandlers.cpp`、`handlers/TransactionHandlers.cpp`、
3//! `extensions/finalization/src/handlers/ProofHandlers.cpp` に合わせている。どれも `#pragma pack(1)` の
4//! リトルエンディアンで、パディングはない。
5//!
6//! バイト列の組み立てと読み取りだけで、通信はしない。どうつなぐか(TLS など)と、どうやりとりするかは使う側が決める。
7
8use std::fmt;
9
10use heika_core::hash::Hash256;
11use heika_core::key::PublicKey;
12use heika_core::network::{GenerationHashSeed, NetworkIdentifier};
13
14/// パケットの見出しの大きさ。見出しを含む全長 `u32` と、種類 `u32`
15pub const HEADER_SIZE: usize = 8;
16
17/// パケットの見出し。catapult の `ionet::PacketHeader`
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub struct Header {
20    /// 見出しを含む全長
21    pub size: u32,
22    pub packet_type: u32,
23}
24
25impl Header {
26    pub fn parse(bytes: &[u8; HEADER_SIZE]) -> Self {
27        let [s0, s1, s2, s3, t0, t1, t2, t3] = *bytes;
28        Self {
29            size: u32::from_le_bytes([s0, s1, s2, s3]),
30            packet_type: u32::from_le_bytes([t0, t1, t2, t3]),
31        }
32    }
33
34    /// 本体の大きさ。全長が見出しより短ければ `None`
35    pub fn body_size(&self) -> Option<usize> {
36        (self.size as usize).checked_sub(HEADER_SIZE)
37    }
38}
39
40/// 見出しを付けたパケット。全長が `u32` に収まらなければ、本体の大きさを `Err` で返す
41pub fn encode(packet_type: u32, body: &[u8]) -> Result<Vec<u8>, usize> {
42    let size = u32::try_from(HEADER_SIZE + body.len()).map_err(|_| body.len())?;
43    let mut packet = Vec::with_capacity(size as usize);
44    packet.extend_from_slice(&size.to_le_bytes());
45    packet.extend_from_slice(&packet_type.to_le_bytes());
46    packet.extend_from_slice(body);
47    Ok(packet)
48}
49
50pub mod extension;
51pub mod partial;
52
53/// catapult の `ionet::PacketType` のうち使うもの。
54pub mod packet_type {
55    pub const PUSH_BLOCK: u32 = 3;
56    pub const PULL_BLOCK: u32 = 4;
57    pub const CHAIN_STATISTICS: u32 = 5;
58    pub const BLOCK_HASHES: u32 = 7;
59    pub const PULL_BLOCKS: u32 = 8;
60    pub const PUSH_TRANSACTIONS: u32 = 9;
61    pub const PULL_TRANSACTIONS: u32 = 10;
62    pub const PUSH_PARTIAL_TRANSACTIONS: u32 = 0x100;
63    pub const PUSH_DETACHED_COSIGNATURES: u32 = 0x101;
64    pub const PULL_PARTIAL_TRANSACTION_INFOS: u32 = 0x102;
65    pub const NODE_DISCOVERY_PUSH_PING: u32 = 0x110;
66    pub const NODE_DISCOVERY_PULL_PING: u32 = 0x111;
67    pub const NODE_DISCOVERY_PUSH_PEERS: u32 = 0x112;
68    pub const NODE_DISCOVERY_PULL_PEERS: u32 = 0x113;
69    pub const TIME_SYNC_NETWORK_TIME: u32 = 0x120;
70    pub const PUSH_FINALIZATION_MESSAGES: u32 = 0x130;
71    pub const PULL_FINALIZATION_MESSAGES: u32 = 0x131;
72    pub const FINALIZATION_STATISTICS: u32 = 0x132;
73    pub const FINALIZATION_PROOF_AT_EPOCH: u32 = 0x133;
74    pub const FINALIZATION_PROOF_AT_HEIGHT: u32 = 0x134;
75    /// 証明の要求(`FINALIZATION_PROOF_AT_EPOCH`、`FINALIZATION_PROOF_AT_HEIGHT`)への応答は、この種類で来る
76    pub const PULL_FINALIZATION_PROOF: u32 = 0x135;
77}
78
79/// `Pull_Blocks` の要求の本体。`height` から最大 `num_blocks` 件、合計 `num_response_bytes` バイトまで
80pub fn pull_blocks_request(height: u64, num_blocks: u32, num_response_bytes: u32) -> [u8; 16] {
81    let mut request = [0; 16];
82    request[..8].copy_from_slice(&height.to_le_bytes());
83    request[8..12].copy_from_slice(&num_blocks.to_le_bytes());
84    request[12..].copy_from_slice(&num_response_bytes.to_le_bytes());
85    request
86}
87
88/// `Pull_Blocks` の要求。catapult の `PullBlocksRequest`
89#[derive(Debug, Clone, Copy, PartialEq, Eq)]
90pub struct PullBlocksRequest {
91    pub height: u64,
92    pub num_blocks: u32,
93    pub num_response_bytes: u32,
94}
95
96impl PullBlocksRequest {
97    pub fn decode(body: &[u8]) -> Result<Self, DecodeError> {
98        let body: &[u8; 16] = fixed(body)?;
99        Ok(Self {
100            height: u64::from_le_bytes(body[..8].try_into().expect("8 bytes")),
101            num_blocks: u32::from_le_bytes(body[8..12].try_into().expect("4 bytes")),
102            num_response_bytes: u32::from_le_bytes(body[12..].try_into().expect("4 bytes")),
103        })
104    }
105}
106
107/// `Block_Hashes` の要求。catapult の `BlockHashesRequest`
108#[derive(Debug, Clone, Copy, PartialEq, Eq)]
109pub struct BlockHashesRequest {
110    pub height: u64,
111    pub num_hashes: u32,
112}
113
114impl BlockHashesRequest {
115    pub fn decode(body: &[u8]) -> Result<Self, DecodeError> {
116        let body: &[u8; 12] = fixed(body)?;
117        Ok(Self {
118            height: u64::from_le_bytes(body[..8].try_into().expect("8 bytes")),
119            num_hashes: u32::from_le_bytes(body[8..].try_into().expect("4 bytes")),
120        })
121    }
122}
123
124/// 長さの決まった本体として読む
125fn fixed<const N: usize>(body: &[u8]) -> Result<&[u8; N], DecodeError> {
126    body.try_into().map_err(|_| DecodeError::BodySize {
127        expected: N,
128        actual: body.len(),
129    })
130}
131
132/// `Pull_Transactions` の要求の本体。catapult の `TransactionsFilter`(Deadline、FeeMultiplier)に、短いハッシュが続く。
133pub fn pull_transactions_request(
134    min_deadline: u64,
135    min_fee_multiplier: u32,
136    known_short_hashes: &[u32],
137) -> Vec<u8> {
138    let mut request = Vec::with_capacity(12 + 4 * known_short_hashes.len());
139    request.extend_from_slice(&min_deadline.to_le_bytes());
140    request.extend_from_slice(&min_fee_multiplier.to_le_bytes());
141    for short_hash in known_short_hashes {
142        request.extend_from_slice(&short_hash.to_le_bytes());
143    }
144    request
145}
146
147/// [`pull_transactions_request`] で書いた要求を読む。期限の下限、手数料の倍率の下限、知っている短いハッシュ
148pub fn read_pull_transactions_request(body: &[u8]) -> Result<(u64, u32, Vec<u32>), DecodeError> {
149    if body.len() < 12 {
150        return Err(DecodeError::Truncated {
151            needed: 12,
152            remaining: body.len(),
153        });
154    }
155    let (filter, hashes) = body.split_at(12);
156    if !hashes.len().is_multiple_of(4) {
157        return Err(DecodeError::BodySize {
158            expected: 12 + hashes.len() / 4 * 4,
159            actual: body.len(),
160        });
161    }
162    let min_deadline = u64::from_le_bytes(filter[..8].try_into().expect("8 bytes"));
163    let min_fee_multiplier = u32::from_le_bytes(filter[8..].try_into().expect("4 bytes"));
164    let known = hashes
165        .as_chunks::<4>()
166        .0
167        .iter()
168        .map(|&bytes| u32::from_le_bytes(bytes))
169        .collect();
170    Ok((min_deadline, min_fee_multiplier, known))
171}
172
173/// catapult の `utils::ToShortHash`。ハッシュの先頭4バイトを u32 として読んだもの。
174/// `Pull_Transactions` で、もう知っているトランザクションを伝えるのに使う。
175pub fn short_hash(hash: &Hash256) -> u32 {
176    u32::from_le_bytes(hash.0[..4].try_into().expect("4 bytes"))
177}
178
179/// `Chain_Statistics` の応答。
180#[derive(Debug, Clone, Copy, PartialEq, Eq)]
181pub struct ChainStatistics {
182    pub height: u64,
183    pub finalized_height: u64,
184    /// catapult では `ScoreHigh` と `ScoreLow` の2つの u64 に分けて送られる
185    pub score: u128,
186}
187
188impl ChainStatistics {
189    const BODY_SIZE: usize = 32;
190
191    pub fn decode(body: &[u8]) -> Result<Self, DecodeError> {
192        let body: &[u8; Self::BODY_SIZE] = body.try_into().map_err(|_| DecodeError::BodySize {
193            expected: Self::BODY_SIZE,
194            actual: body.len(),
195        })?;
196        let u64_at = |offset: usize| {
197            u64::from_le_bytes(body[offset..offset + 8].try_into().expect("8 bytes"))
198        };
199        Ok(Self {
200            height: u64_at(0),
201            finalized_height: u64_at(8),
202            score: (u128::from(u64_at(16)) << 64) | u128::from(u64_at(24)),
203        })
204    }
205
206    pub fn encode(&self) -> [u8; Self::BODY_SIZE] {
207        let mut body = [0; Self::BODY_SIZE];
208        body[..8].copy_from_slice(&self.height.to_le_bytes());
209        body[8..16].copy_from_slice(&self.finalized_height.to_le_bytes());
210        body[16..24].copy_from_slice(&((self.score >> 64) as u64).to_le_bytes());
211        body[24..].copy_from_slice(&(self.score as u64).to_le_bytes());
212        body
213    }
214}
215
216/// `Time_Sync_Network_Time` の応答。相手のネットワーク時刻(Nemesis からのミリ秒)で、要求を受け取った時刻と
217/// 応答を送った時刻。catapult の `CommunicationTimestamps`
218#[derive(Debug, Clone, Copy, PartialEq, Eq)]
219pub struct NetworkTime {
220    pub receive: u64,
221    pub send: u64,
222}
223
224impl NetworkTime {
225    const BODY_SIZE: usize = 16;
226
227    pub fn decode(body: &[u8]) -> Result<Self, DecodeError> {
228        let body: &[u8; Self::BODY_SIZE] = body.try_into().map_err(|_| DecodeError::BodySize {
229            expected: Self::BODY_SIZE,
230            actual: body.len(),
231        })?;
232        let u64_at = |offset: usize| {
233            u64::from_le_bytes(body[offset..offset + 8].try_into().expect("8 bytes"))
234        };
235        // catapult では SendTimestamp、ReceiveTimestamp の順
236        Ok(Self {
237            send: u64_at(0),
238            receive: u64_at(8),
239        })
240    }
241
242    pub fn encode(&self) -> [u8; Self::BODY_SIZE] {
243        let mut body = [0; Self::BODY_SIZE];
244        body[..8].copy_from_slice(&self.send.to_le_bytes());
245        body[8..].copy_from_slice(&self.receive.to_le_bytes());
246        body
247    }
248
249    /// 相手の時計が、自分の時計よりどれだけ進んでいるか(ミリ秒)。`local_send` と `local_receive` は、自分の時計で
250    /// 要求を送った時刻と応答を受け取った時刻。往復にかかった時間の半分を行きの時間とみなす。catapult の
251    /// `TimeSynchronizationSample::timeOffsetToRemote`
252    pub fn offset(&self, local_send: u64, local_receive: u64) -> i64 {
253        let signed = |timestamp: u64| i64::try_from(timestamp).unwrap_or(i64::MAX);
254        let local = signed(local_receive) - signed(local_send);
255        let remote = signed(self.send) - signed(self.receive);
256        signed(self.receive) - signed(local_send) - (local - remote) / 2
257    }
258}
259
260/// catapult の `NodeVersion`。1バイトずつ上位から major.minor.revision.build。
261#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
262pub struct NodeVersion(pub u32);
263
264impl fmt::Display for NodeVersion {
265    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
266        let [major, minor, revision, build] = self.0.to_be_bytes();
267        write!(f, "{major}.{minor}.{revision}.{build}")
268    }
269}
270
271/// catapult の `NodeRoles`。ビットフラグ。
272#[derive(Debug, Clone, Copy, PartialEq, Eq)]
273pub struct NodeRoles(pub u32);
274
275impl NodeRoles {
276    pub const PEER: Self = Self(0x01);
277    pub const API: Self = Self(0x02);
278    pub const VOTING: Self = Self(0x04);
279
280    const NAMES: [(u32, &str); 5] = [
281        (0x01, "Peer"),
282        (0x02, "Api"),
283        (0x04, "Voting"),
284        (0x40, "IPv4"),
285        (0x80, "IPv6"),
286    ];
287
288    /// catapult の設定ファイルでの名前(`Peer`、`Api` など)から、そのビット。知らない名前なら `None`。
289    pub fn from_name(name: &str) -> Option<Self> {
290        Self::NAMES
291            .iter()
292            .find(|(_, known)| *known == name)
293            .map(|(bit, _)| Self(*bit))
294    }
295
296    /// `roles` のビットがすべて立っているか。
297    pub fn contains(self, roles: Self) -> bool {
298        self.0 & roles.0 == roles.0
299    }
300
301    /// catapult の設定ファイル(peers-p2p.json など)の書き方。`IPv4,Peer` のように `,` で区切る。
302    /// catapult は知らない名前があると読み込めないので、知らないビットは落とす。
303    pub fn to_config_value(self) -> String {
304        Self::NAMES
305            .iter()
306            .filter(|(bit, _)| self.0 & bit != 0)
307            .map(|(_, name)| *name)
308            .collect::<Vec<_>>()
309            .join(",")
310    }
311
312    /// 立っているロールの名前。知らないビットは、まとめて `0x100` のような16進で最後に置く。
313    pub fn names(self) -> Vec<String> {
314        let mut names: Vec<String> = Self::NAMES
315            .iter()
316            .filter(|(bit, _)| self.0 & bit != 0)
317            .map(|(_, name)| (*name).to_owned())
318            .collect();
319        let known = Self::NAMES.iter().fold(0, |bits, (bit, _)| bits | bit);
320        if self.0 & !known != 0 {
321            names.push(format!("{:#x}", self.0 & !known));
322        }
323        names
324    }
325}
326
327impl fmt::Display for NodeRoles {
328    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
329        let names = self.names();
330        if names.is_empty() {
331            f.write_str("None")
332        } else {
333            f.write_str(&names.join("|"))
334        }
335    }
336}
337
338/// catapult の `ionet::NetworkNode`。ノードの公開情報。
339///
340/// ```text
341/// u32  Size  u32 Version  [32] IdentityKey  [32] NetworkGenerationHashSeed
342/// u32  Roles  u16 Port  u8 NetworkIdentifier  u8 HostSize  u8 FriendlyNameSize
343/// ...  host(HostSize バイト) friendly name(FriendlyNameSize バイト)
344/// ```
345///
346/// host と friendly name はノードが自分で名乗るもので、何が入っているかわからない。表示するときは制御文字に気をつける。
347#[derive(Debug, Clone, PartialEq, Eq)]
348pub struct NetworkNode {
349    pub version: NodeVersion,
350    /// ノードの CA の公開鍵
351    pub identity_key: PublicKey,
352    pub network_generation_hash_seed: GenerationHashSeed,
353    pub roles: NodeRoles,
354    pub port: u16,
355    pub network_identifier: NetworkIdentifier,
356    pub host: String,
357    pub friendly_name: String,
358}
359
360impl NetworkNode {
361    const FIXED_SIZE: usize = 81;
362
363    /// エンティティ1件(`Size` から最後の文字列まで)をデコードする。
364    pub fn decode(entity: &[u8]) -> Result<Self, DecodeError> {
365        let fixed: &[u8; Self::FIXED_SIZE] = entity
366            .get(..Self::FIXED_SIZE)
367            .and_then(|bytes| bytes.try_into().ok())
368            .ok_or(DecodeError::EntityTooSmall {
369                size: entity.len(),
370                minimum: Self::FIXED_SIZE,
371            })?;
372        let u32_at = |offset: usize| {
373            u32::from_le_bytes(fixed[offset..offset + 4].try_into().expect("4 bytes"))
374        };
375        let declared = u32_at(0) as usize;
376        if declared != entity.len() {
377            return Err(DecodeError::SizeMismatch {
378                declared,
379                actual: entity.len(),
380            });
381        }
382        let host_size = usize::from(fixed[79]);
383        let friendly_name_size = usize::from(fixed[80]);
384        let expected = Self::FIXED_SIZE + host_size + friendly_name_size;
385        if declared != expected {
386            return Err(DecodeError::SizeMismatch {
387                declared,
388                actual: expected,
389            });
390        }
391
392        let (host, friendly_name) = entity[Self::FIXED_SIZE..].split_at(host_size);
393        Ok(Self {
394            version: NodeVersion(u32_at(4)),
395            identity_key: PublicKey(fixed[8..40].try_into().expect("32 bytes")),
396            network_generation_hash_seed: GenerationHashSeed(
397                fixed[40..72].try_into().expect("32 bytes"),
398            ),
399            roles: NodeRoles(u32_at(72)),
400            port: u16::from_le_bytes([fixed[76], fixed[77]]),
401            network_identifier: NetworkIdentifier(fixed[78]),
402            // 名前は表示に使うだけなので、壊れた UTF-8 でもリスト全体を失敗させない
403            host: String::from_utf8_lossy(host).into_owned(),
404            friendly_name: String::from_utf8_lossy(friendly_name).into_owned(),
405        })
406    }
407
408    /// エンティティ1件にする。host か friendly name が 255 バイトを超えるなら `None`
409    pub fn encode(&self) -> Option<Vec<u8>> {
410        let host_size = u8::try_from(self.host.len()).ok()?;
411        let friendly_name_size = u8::try_from(self.friendly_name.len()).ok()?;
412        let size = Self::FIXED_SIZE + self.host.len() + self.friendly_name.len();
413        let mut entity = Vec::with_capacity(size);
414        entity.extend_from_slice(&(size as u32).to_le_bytes());
415        entity.extend_from_slice(&self.version.0.to_le_bytes());
416        entity.extend_from_slice(&self.identity_key.0);
417        entity.extend_from_slice(&self.network_generation_hash_seed.0);
418        entity.extend_from_slice(&self.roles.0.to_le_bytes());
419        entity.extend_from_slice(&self.port.to_le_bytes());
420        entity.push(self.network_identifier.0);
421        entity.push(host_size);
422        entity.push(friendly_name_size);
423        entity.extend_from_slice(self.host.as_bytes());
424        entity.extend_from_slice(self.friendly_name.as_bytes());
425        Some(entity)
426    }
427
428    /// `Node_Discovery_Pull_Peers` の応答の本体(`NetworkNode` の並び)をデコードする。
429    pub fn decode_list(body: &[u8]) -> Result<Vec<Self>, DecodeError> {
430        split_size_prefixed(body)?
431            .into_iter()
432            .map(Self::decode)
433            .collect()
434    }
435}
436
437/// 先頭に `Size: u32`(自身を含む全長)を持つエンティティが隙間なく並んだ本体を、1件ずつに切り出す。
438pub fn split_size_prefixed(mut body: &[u8]) -> Result<Vec<&[u8]>, DecodeError> {
439    let mut entities = Vec::new();
440    while !body.is_empty() {
441        let size = body
442            .get(..4)
443            .map(|bytes| u32::from_le_bytes(bytes.try_into().expect("4 bytes")) as usize)
444            .ok_or(DecodeError::Truncated {
445                needed: 4,
446                remaining: body.len(),
447            })?;
448        if size < 4 {
449            return Err(DecodeError::EntityTooSmall { size, minimum: 4 });
450        }
451        let (entity, rest) = body.split_at_checked(size).ok_or(DecodeError::Truncated {
452            needed: size,
453            remaining: body.len(),
454        })?;
455        entities.push(entity);
456        body = rest;
457    }
458    Ok(entities)
459}
460
461/// 応答を読めない理由。
462#[derive(Debug, Clone, PartialEq, Eq)]
463pub enum DecodeError {
464    /// 本体の長さが決まっているのに合わない
465    BodySize { expected: usize, actual: usize },
466    /// 残りのバイト数が、読もうとした長さに足りない
467    Truncated { needed: usize, remaining: usize },
468    /// エンティティが固定部分より短い
469    EntityTooSmall { size: usize, minimum: usize },
470    /// 先頭の Size と、実際の長さや中身から計算した長さが合わない
471    SizeMismatch { declared: usize, actual: usize },
472    /// 0 で埋めるはずのところが0でない
473    NonZeroPadding,
474    /// 値が決まりに合わない。中身はわけ
475    InvalidValue(&'static str),
476}
477
478impl fmt::Display for DecodeError {
479    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
480        match self {
481            Self::BodySize { expected, actual } => {
482                write!(f, "本体が {expected} バイトのはずが {actual} バイトでした")
483            }
484            Self::Truncated { needed, remaining } => {
485                write!(f, "{needed} バイト必要ですが残りは {remaining} バイトです")
486            }
487            Self::EntityTooSmall { size, minimum } => {
488                write!(f, "{size} バイトしかありません(最低 {minimum} バイト)")
489            }
490            Self::NonZeroPadding => write!(f, "0 で埋めるはずのところが0ではありません"),
491            Self::InvalidValue(reason) => f.write_str(reason),
492            Self::SizeMismatch { declared, actual } => {
493                write!(
494                    f,
495                    "Size は {declared} バイトですが実際は {actual} バイトです"
496                )
497            }
498        }
499    }
500}
501
502impl std::error::Error for DecodeError {}
503
504#[cfg(test)]
505mod tests {
506    use super::*;
507
508    /// catapult の `NetworkNode` の並びで書いたもの
509    fn network_node(host: &[u8], friendly_name: &[u8]) -> Vec<u8> {
510        let mut bytes = Vec::new();
511        let size = 81 + host.len() + friendly_name.len();
512        bytes.extend_from_slice(&(size as u32).to_le_bytes());
513        bytes.extend_from_slice(&0x0001_0203_u32.to_le_bytes());
514        bytes.extend_from_slice(&[0x11; 32]);
515        bytes.extend_from_slice(&[0x22; 32]);
516        bytes.extend_from_slice(&0x43_u32.to_le_bytes());
517        bytes.extend_from_slice(&7900_u16.to_le_bytes());
518        bytes.push(0x68);
519        bytes.push(host.len() as u8);
520        bytes.push(friendly_name.len() as u8);
521        bytes.extend_from_slice(host);
522        bytes.extend_from_slice(friendly_name);
523        bytes
524    }
525
526    #[test]
527    fn decodes_a_network_node() {
528        let node = NetworkNode::decode(&network_node(b"node.example", b"example")).unwrap();
529        assert_eq!(node.version.to_string(), "0.1.2.3");
530        assert_eq!(node.identity_key, PublicKey([0x11; 32]));
531        assert_eq!(
532            node.network_generation_hash_seed,
533            GenerationHashSeed([0x22; 32])
534        );
535        assert_eq!(node.roles.to_string(), "Peer|Api|IPv4");
536        assert_eq!(node.port, 7900);
537        assert_eq!(node.network_identifier, NetworkIdentifier::MAINNET);
538        assert_eq!(node.host, "node.example");
539        assert_eq!(node.friendly_name, "example");
540    }
541
542    #[test]
543    fn encodes_a_network_node_as_catapult_does() {
544        let bytes = network_node(b"node.example", b"example");
545        assert_eq!(
546            NetworkNode::decode(&bytes).unwrap().encode().unwrap(),
547            bytes
548        );
549        let mut node = NetworkNode::decode(&bytes).unwrap();
550        node.host = "h".repeat(256);
551        assert_eq!(node.encode(), None);
552    }
553
554    #[test]
555    fn encodes_and_decodes_fixed_bodies() {
556        let statistics = ChainStatistics {
557            height: 1,
558            finalized_height: 2,
559            score: (3 << 64) | 4,
560        };
561        let body = statistics.encode();
562        assert_eq!(&body[16..24], &3u64.to_le_bytes());
563        assert_eq!(&body[24..], &4u64.to_le_bytes());
564        assert_eq!(ChainStatistics::decode(&body).unwrap(), statistics);
565        let time = NetworkTime {
566            receive: 5,
567            send: 6,
568        };
569        assert_eq!(&time.encode()[..8], &6u64.to_le_bytes());
570        assert_eq!(NetworkTime::decode(&time.encode()).unwrap(), time);
571        assert_eq!(
572            PullBlocksRequest::decode(&pull_blocks_request(7, 8, 9)).unwrap(),
573            PullBlocksRequest {
574                height: 7,
575                num_blocks: 8,
576                num_response_bytes: 9
577            }
578        );
579        let hashes = [&10u64.to_le_bytes()[..], &11u32.to_le_bytes()].concat();
580        assert_eq!(
581            BlockHashesRequest::decode(&hashes).unwrap(),
582            BlockHashesRequest {
583                height: 10,
584                num_hashes: 11
585            }
586        );
587        assert_eq!(
588            BlockHashesRequest::decode(&hashes[1..]),
589            Err(DecodeError::BodySize {
590                expected: 12,
591                actual: 11
592            })
593        );
594    }
595
596    #[test]
597    fn decodes_a_list_of_network_nodes() {
598        let body = [network_node(b"a", b""), network_node(b"", b"b")].concat();
599        let nodes = NetworkNode::decode_list(&body).unwrap();
600        assert_eq!(nodes.len(), 2);
601        assert_eq!(
602            (nodes[0].host.as_str(), nodes[1].friendly_name.as_str()),
603            ("a", "b")
604        );
605        assert_eq!(NetworkNode::decode_list(&[]).unwrap(), []);
606    }
607
608    #[test]
609    fn rejects_a_network_node_with_inconsistent_sizes() {
610        let mut bytes = network_node(b"host", b"name");
611        bytes.push(0);
612        assert_eq!(
613            NetworkNode::decode(&bytes),
614            Err(DecodeError::SizeMismatch {
615                declared: 89,
616                actual: 90
617            })
618        );
619        let mut bytes = network_node(b"host", b"name");
620        bytes[79] = 5;
621        assert!(matches!(
622            NetworkNode::decode(&bytes),
623            Err(DecodeError::SizeMismatch { .. })
624        ));
625        assert!(matches!(
626            NetworkNode::decode(&bytes[..80]),
627            Err(DecodeError::EntityTooSmall { .. })
628        ));
629    }
630
631    #[test]
632    fn decodes_chain_statistics() {
633        let mut body = Vec::new();
634        for value in [10_u64, 8, 1, 2] {
635            body.extend_from_slice(&value.to_le_bytes());
636        }
637        assert_eq!(
638            ChainStatistics::decode(&body),
639            Ok(ChainStatistics {
640                height: 10,
641                finalized_height: 8,
642                score: (1 << 64) | 2,
643            })
644        );
645        assert!(ChainStatistics::decode(&body[..31]).is_err());
646    }
647
648    #[test]
649    fn decodes_network_time_and_computes_the_offset() {
650        let mut body = Vec::new();
651        for value in [5_020_u64, 5_000] {
652            body.extend_from_slice(&value.to_le_bytes());
653        }
654        let time = NetworkTime::decode(&body).unwrap();
655        assert_eq!(
656            time,
657            NetworkTime {
658                receive: 5_000,
659                send: 5_020
660            }
661        );
662        assert!(NetworkTime::decode(&body[..15]).is_err());
663        // 往復 120 ミリ秒のうち、相手の中で 20 ミリ秒かかったので、行きは 50 ミリ秒。相手は 3 秒進んでいる
664        assert_eq!(time.offset(1_950, 2_070), 3_000);
665        // 遅れているときは負になる
666        let behind = NetworkTime {
667            receive: 1_000,
668            send: 1_000,
669        };
670        assert_eq!(behind.offset(1_950, 2_050), -1_000);
671    }
672
673    #[test]
674    fn writes_a_pull_transactions_request() {
675        let mut hash = [0; 32];
676        hash[..4].copy_from_slice(&[0xaa, 0xbb, 0xcc, 0xdd]);
677        let short = short_hash(&Hash256(hash));
678        assert_eq!(short, 0xddcc_bbaa);
679        assert_eq!(
680            pull_transactions_request(0x0102_0304_0506_0708, 100, &[short]),
681            [
682                &[8, 7, 6, 5, 4, 3, 2, 1][..],
683                &[100, 0, 0, 0],
684                &[0xaa, 0xbb, 0xcc, 0xdd]
685            ]
686            .concat()
687        );
688        assert_eq!(pull_transactions_request(0, 0, &[]), [0; 12]);
689    }
690
691    #[test]
692    fn reads_a_pull_transactions_request() {
693        let request = pull_transactions_request(0x0102_0304_0506_0708, 100, &[1, 0xddcc_bbaa]);
694        assert_eq!(
695            read_pull_transactions_request(&request),
696            Ok((0x0102_0304_0506_0708, 100, vec![1, 0xddcc_bbaa]))
697        );
698        assert_eq!(
699            read_pull_transactions_request(&[0; 11]),
700            Err(DecodeError::Truncated {
701                needed: 12,
702                remaining: 11
703            })
704        );
705        assert_eq!(
706            read_pull_transactions_request(&[0; 14]),
707            Err(DecodeError::BodySize {
708                expected: 12,
709                actual: 14
710            })
711        );
712    }
713
714    #[test]
715    fn writes_and_reads_headers() {
716        let packet = encode(5, &[1, 2, 3]).unwrap();
717        assert_eq!(packet, [11, 0, 0, 0, 5, 0, 0, 0, 1, 2, 3]);
718        let header = Header::parse(packet[..HEADER_SIZE].try_into().unwrap());
719        assert_eq!(
720            header,
721            Header {
722                size: 11,
723                packet_type: 5
724            }
725        );
726        assert_eq!(header.body_size(), Some(3));
727        assert_eq!(Header::parse(&[7, 0, 0, 0, 1, 0, 0, 0]).body_size(), None);
728    }
729
730    #[test]
731    fn writes_a_pull_blocks_request() {
732        assert_eq!(
733            pull_blocks_request(0x0102, 3, 0x0405),
734            [2, 1, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 5, 4, 0, 0]
735        );
736    }
737
738    #[test]
739    fn names_unknown_roles() {
740        assert_eq!(NodeRoles(0).to_string(), "None");
741        assert_eq!(NodeRoles(0x105).to_string(), "Peer|Voting|0x100");
742    }
743
744    #[test]
745    fn writes_roles_for_config_without_unknown_bits() {
746        assert_eq!(NodeRoles(0x43).to_config_value(), "Peer,Api,IPv4");
747        assert_eq!(NodeRoles(0x141).to_config_value(), "Peer,IPv4");
748        assert!(NodeRoles(0x41).contains(NodeRoles::PEER));
749        assert!(!NodeRoles(0x42).contains(NodeRoles::PEER));
750    }
751
752    #[test]
753    fn reads_role_names_like_catapult_config() {
754        assert_eq!(NodeRoles::from_name("Api"), Some(NodeRoles(0x02)));
755        assert_eq!(NodeRoles::from_name("IPv4"), Some(NodeRoles(0x40)));
756        assert_eq!(NodeRoles::from_name("api"), None);
757    }
758
759    #[test]
760    fn splits_entities_and_rejects_truncated_ones() {
761        let body = [&5_u32.to_le_bytes()[..], b"x", &4_u32.to_le_bytes()].concat();
762        assert_eq!(
763            split_size_prefixed(&body).unwrap(),
764            [&body[..5], &body[5..]]
765        );
766        assert!(split_size_prefixed(&body[..7]).is_err());
767        assert!(split_size_prefixed(&3_u32.to_le_bytes()).is_err());
768    }
769}