Files
nym/common/nymsphinx/forwarding/src/packet.rs
T
Jędrzej Stuczyński e5afd54ce0 Feature/node status api (#680)
* Basic storage stub

* New models for new node status api

* Route handling

* Mounting new routes

* Missing selective commit

* Moved network monitor related files to separate package

* Starting to see some sqlx action

* Schema updates

* Log statement upon finished migration

* Removed old diesel related imports

* Converted mixnode cache initialisation into a fairing

* Moved cache related functionalities to separate package

Also defined staging there

* Created run method for validator cache + removed unwrap

* Removed old node-status-api types and left bunch of todo placeholders in their place

* Fixed managing validatorcache

* Status reports are starting to get constructed

* Submitting some dummy results to the database

* Removing duplicate code for generating reports

* Removed statuses older than 48h

* Initial attempt at trying to obtain reports for all active nodes

* Removed duplicates from the full report

* Grabbing uptime history

* Updating historical uptimes of active nodes

* Updated sqlx-data.json

* Removed all placeholder foomp owner values

* Changed Layer serde behaviour for easier usage

* Extended validator api config

* Initial (seems working !) integration with network monitor

* Added database path configuration to config

* Using ValidatorCache in NetworkMonitor

* Flag indicating whether validator cache has been initialised

* Introduced a locla-only route for reward script to perform daily chores

* Flag to save config to a file

* Moved spawning of receiving future to run method rather than new

* Removed arguments that dont make sense to be configured via CLI

* Removed dead code from config file

* More dead code removal

* Added validator API to CI

* Corrected manifest-path arguments

* Constructing network monitor by passing config

* Combined validator API CI with the main CI file

* Using query_as for NodeStatus

* Checking if historical uptimes were already calculated on particular day

* Making id field NOT NULL

* More query_as! action

* Updated sqlx-data.json

* Removed unused chrono feature

* Renamed the migration file

* Changed default validator endpoint to point to local validator

* Removing unnecessary clone

* More appropriate naming

* Removed dead code

* Lock file updates

* Updated network monitor address in contract code

* Don't stage node status api if network monitor is disabled

* cargo fmt

* Updated all license notices to SPDX
2021-07-19 14:02:47 +01:00

118 lines
3.7 KiB
Rust

// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use nymsphinx_addressing::nodes::{NymNodeRoutingAddress, NymNodeRoutingAddressError};
use nymsphinx_params::{PacketMode, PacketSize};
use nymsphinx_types::SphinxPacket;
use std::convert::TryFrom;
use std::fmt::{self, Display, Formatter};
#[derive(Debug)]
pub enum MixPacketFormattingError {
TooFewBytesProvided,
InvalidPacketMode,
InvalidPacketSize(usize),
InvalidAddress,
MalformedSphinxPacket,
}
impl Display for MixPacketFormattingError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
use MixPacketFormattingError::*;
match self {
TooFewBytesProvided => write!(f, "Too few bytes provided to recover from bytes"),
InvalidAddress => write!(f, "address field was incorrectly encoded"),
InvalidPacketSize(actual) =>
write!(
f,
"received request had invalid size. (actual: {}, but expected one of: {} (ACK), {} (REGULAR), {} (EXTENDED))",
actual, PacketSize::AckPacket.size(), PacketSize::RegularPacket.size(), PacketSize::ExtendedPacket.size()
),
MalformedSphinxPacket => write!(f, "received sphinx packet was malformed"),
InvalidPacketMode => write!(f, "provided packet mode is invalid")
}
}
}
impl std::error::Error for MixPacketFormattingError {}
impl From<NymNodeRoutingAddressError> for MixPacketFormattingError {
fn from(_: NymNodeRoutingAddressError) -> Self {
MixPacketFormattingError::InvalidAddress
}
}
pub struct MixPacket {
next_hop: NymNodeRoutingAddress,
sphinx_packet: SphinxPacket,
packet_mode: PacketMode,
}
impl MixPacket {
pub fn new(
next_hop: NymNodeRoutingAddress,
sphinx_packet: SphinxPacket,
packet_mode: PacketMode,
) -> Self {
MixPacket {
next_hop,
sphinx_packet,
packet_mode,
}
}
pub fn next_hop(&self) -> NymNodeRoutingAddress {
self.next_hop
}
pub fn sphinx_packet(&self) -> &SphinxPacket {
&self.sphinx_packet
}
pub fn into_sphinx_packet(self) -> SphinxPacket {
self.sphinx_packet
}
pub fn packet_mode(&self) -> PacketMode {
self.packet_mode
}
// the message is formatted as follows:
// PACKET_MODE || FIRST_HOP || SPHINX_PACKET
pub fn try_from_bytes(b: &[u8]) -> Result<Self, MixPacketFormattingError> {
let packet_mode = match PacketMode::try_from(b[0]) {
Ok(mode) => mode,
Err(_) => return Err(MixPacketFormattingError::InvalidPacketMode),
};
let next_hop = NymNodeRoutingAddress::try_from_bytes(&b[1..])?;
let addr_offset = next_hop.bytes_min_len();
let sphinx_packet_data = &b[addr_offset + 1..];
let packet_size = sphinx_packet_data.len();
if PacketSize::get_type(packet_size).is_err() {
Err(MixPacketFormattingError::InvalidPacketSize(packet_size))
} else {
let sphinx_packet = match SphinxPacket::from_bytes(sphinx_packet_data) {
Ok(packet) => packet,
Err(_) => return Err(MixPacketFormattingError::MalformedSphinxPacket),
};
Ok(MixPacket {
next_hop,
sphinx_packet,
packet_mode,
})
}
}
pub fn into_bytes(self) -> Vec<u8> {
std::iter::once(self.packet_mode as u8)
.chain(self.next_hop.as_bytes().into_iter())
.chain(self.sphinx_packet.to_bytes().into_iter())
.collect()
}
}
// TODO: test for serialization and errors!