Skip to content
Snippets Groups Projects
Commit 56ee5537 authored by Éloïs's avatar Éloïs
Browse files

[ref] ws2pv2: use pkstl

parent 08672b09
No related branches found
No related tags found
No related merge requests found
Showing
with 261 additions and 384 deletions
...@@ -783,7 +783,6 @@ dependencies = [ ...@@ -783,7 +783,6 @@ dependencies = [
"failure 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", "failure 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
"log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)",
"maplit 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "maplit 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)",
"rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)",
"serde 1.0.99 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.99 (registry+https://github.com/rust-lang/crates.io-index)",
"serde_derive 1.0.99 (registry+https://github.com/rust-lang/crates.io-index)", "serde_derive 1.0.99 (registry+https://github.com/rust-lang/crates.io-index)",
"serde_json 1.0.40 (registry+https://github.com/rust-lang/crates.io-index)", "serde_json 1.0.40 (registry+https://github.com/rust-lang/crates.io-index)",
...@@ -796,7 +795,6 @@ name = "durs-ws2p-messages" ...@@ -796,7 +795,6 @@ name = "durs-ws2p-messages"
version = "0.3.0-dev" version = "0.3.0-dev"
dependencies = [ dependencies = [
"bincode 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "bincode 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)",
"byteorder 1.2.7 (registry+https://github.com/rust-lang/crates.io-index)",
"dubp-block-doc 0.1.0", "dubp-block-doc 0.1.0",
"dubp-common-doc 0.1.0", "dubp-common-doc 0.1.0",
"dubp-currency-params 0.2.0", "dubp-currency-params 0.2.0",
...@@ -806,10 +804,9 @@ dependencies = [ ...@@ -806,10 +804,9 @@ dependencies = [
"durs-network-documents 0.4.0", "durs-network-documents 0.4.0",
"failure 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", "failure 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
"log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)",
"pkstl 0.1.0",
"pretty_assertions 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", "pretty_assertions 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)",
"serde 1.0.99 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.99 (registry+https://github.com/rust-lang/crates.io-index)",
"serde_derive 1.0.99 (registry+https://github.com/rust-lang/crates.io-index)",
"serde_json 1.0.40 (registry+https://github.com/rust-lang/crates.io-index)",
] ]
[[package]] [[package]]
...@@ -830,7 +827,7 @@ dependencies = [ ...@@ -830,7 +827,7 @@ dependencies = [
"durs-ws2p-messages 0.3.0-dev", "durs-ws2p-messages 0.3.0-dev",
"failure 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", "failure 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
"log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)",
"maplit 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "pkstl 0.1.0",
"pretty_assertions 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", "pretty_assertions 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)",
"rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)", "rand 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)",
"serde 1.0.99 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.99 (registry+https://github.com/rust-lang/crates.io-index)",
...@@ -1087,17 +1084,6 @@ name = "libc" ...@@ -1087,17 +1084,6 @@ name = "libc"
version = "0.2.62" version = "0.2.62"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "libz-sys"
version = "1.0.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"cc 1.0.40 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.62 (registry+https://github.com/rust-lang/crates.io-index)",
"pkg-config 0.3.15 (registry+https://github.com/rust-lang/crates.io-index)",
"vcpkg 0.2.7 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]] [[package]]
name = "log" name = "log"
version = "0.4.8" version = "0.4.8"
...@@ -2270,8 +2256,6 @@ dependencies = [ ...@@ -2270,8 +2256,6 @@ dependencies = [
"byteorder 1.2.7 (registry+https://github.com/rust-lang/crates.io-index)", "byteorder 1.2.7 (registry+https://github.com/rust-lang/crates.io-index)",
"bytes 0.4.12 (registry+https://github.com/rust-lang/crates.io-index)", "bytes 0.4.12 (registry+https://github.com/rust-lang/crates.io-index)",
"httparse 1.3.4 (registry+https://github.com/rust-lang/crates.io-index)", "httparse 1.3.4 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.62 (registry+https://github.com/rust-lang/crates.io-index)",
"libz-sys 1.0.25 (registry+https://github.com/rust-lang/crates.io-index)",
"log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)",
"mio 0.6.19 (registry+https://github.com/rust-lang/crates.io-index)", "mio 0.6.19 (registry+https://github.com/rust-lang/crates.io-index)",
"mio-extras 2.0.5 (registry+https://github.com/rust-lang/crates.io-index)", "mio-extras 2.0.5 (registry+https://github.com/rust-lang/crates.io-index)",
...@@ -2366,7 +2350,6 @@ dependencies = [ ...@@ -2366,7 +2350,6 @@ dependencies = [
"checksum lazy_static 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "bc5729f27f159ddd61f4df6228e827e86643d4d3e7c32183cb30a1c08f604a14" "checksum lazy_static 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "bc5729f27f159ddd61f4df6228e827e86643d4d3e7c32183cb30a1c08f604a14"
"checksum lazycell 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "b294d6fa9ee409a054354afc4352b0b9ef7ca222c69b8812cbea9e7d2bf3783f" "checksum lazycell 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "b294d6fa9ee409a054354afc4352b0b9ef7ca222c69b8812cbea9e7d2bf3783f"
"checksum libc 0.2.62 (registry+https://github.com/rust-lang/crates.io-index)" = "34fcd2c08d2f832f376f4173a231990fa5aef4e99fb569867318a227ef4c06ba" "checksum libc 0.2.62 (registry+https://github.com/rust-lang/crates.io-index)" = "34fcd2c08d2f832f376f4173a231990fa5aef4e99fb569867318a227ef4c06ba"
"checksum libz-sys 1.0.25 (registry+https://github.com/rust-lang/crates.io-index)" = "2eb5e43362e38e2bca2fd5f5134c4d4564a23a5c28e9b95411652021a8675ebe"
"checksum log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)" = "14b6052be84e6b71ab17edffc2eeabf5c2c3ae1fdb464aae35ac50c67a44e1f7" "checksum log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)" = "14b6052be84e6b71ab17edffc2eeabf5c2c3ae1fdb464aae35ac50c67a44e1f7"
"checksum maplit 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "08cbb6b4fef96b6d77bfc40ec491b1690c779e77b05cd9f07f787ed376fd4c43" "checksum maplit 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "08cbb6b4fef96b6d77bfc40ec491b1690c779e77b05cd9f07f787ed376fd4c43"
"checksum matches 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)" = "7ffc5c5338469d4d3ea17d269fa8ea3512ad247247c30bd2df69e68309ed0a08" "checksum matches 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)" = "7ffc5c5338469d4d3ea17d269fa8ea3512ad247247c30bd2df69e68309ed0a08"
......
// Copyright (C) 2017-2019 The AXIOM TEAM Association.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//! Generic code for signing data in binary format
use super::*;
use serde::{Deserialize, Serialize};
/// Signatureable in binary format
pub trait BinSignable<'de>: Serialize + Deserialize<'de> {
/// Return entity issuer pubkey
fn issuer_pubkey(&self) -> PubKey;
/// Return signature
fn signature(&self) -> Option<Sig>;
/// Change signature
fn set_signature(&mut self, _signature: Sig);
/// Get binary datas without signature
fn get_bin_without_sig(&self) -> Result<Vec<u8>, failure::Error>;
/// Add signature to bin datas
fn add_sig_to_bin_datas(&self, bin_datas: &mut Vec<u8>);
/// Sign entity with a signator
fn sign(&mut self, signator: &SignatorEnum) -> Result<Vec<u8>, SignError> {
if self.signature().is_some() {
return Err(SignError::AlreadySign);
}
match self.issuer_pubkey() {
PubKey::Ed25519(_) => {
let mut bin_msg = self
.get_bin_without_sig()
.map_err(|e| SignError::SerdeError(e.to_string()))?;
let sig = signator.sign(&bin_msg);
self.set_signature(sig);
self.add_sig_to_bin_datas(&mut bin_msg);
Ok(bin_msg)
}
_ => Err(SignError::WrongAlgo),
}
}
/// Check signature of entity
fn verify(&self) -> Result<(), SigError> {
if let Some(signature) = self.signature() {
match self.issuer_pubkey() {
PubKey::Ed25519(pubkey) => match signature {
Sig::Ed25519(sig) => {
let signed_part: Vec<u8> = self
.get_bin_without_sig()
.map_err(|e| SigError::SerdeError(format!("{}", e)))?;
pubkey.verify(&signed_part, &sig)
/*
if pubkey.verify(&signed_part, &sig) {
Ok(())
} else {
Err(SigError::InvalidSig())
}
*/
}
_ => Err(SigError::NotSameAlgo),
},
_ => Err(SigError::NotSameAlgo),
}
} else {
Err(SigError::NotSig)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use bincode;
#[derive(Deserialize, Serialize)]
struct BinSignableTestImpl {
datas: Vec<u8>,
issuer: PubKey,
sig: Option<Sig>,
}
impl BinSignable<'_> for BinSignableTestImpl {
#[inline]
fn add_sig_to_bin_datas(&self, bin_datas: &mut Vec<u8>) {
bin_datas
.extend_from_slice(&bincode::serialize(&self.sig).expect("Fail to binarize sig !"));
}
#[inline]
fn get_bin_without_sig(&self) -> Result<Vec<u8>, failure::Error> {
let mut bin_msg = bincode::serialize(&self)?;
let sig_size = bincode::serialized_size(&self.signature())?;
let bin_msg_len = bin_msg.len();
bin_msg.truncate(bin_msg_len - (sig_size as usize));
Ok(bin_msg)
}
fn issuer_pubkey(&self) -> PubKey {
self.issuer
}
fn signature(&self) -> Option<Sig> {
self.sig
}
fn set_signature(&mut self, new_signature: Sig) {
self.sig = Some(new_signature);
}
}
#[test]
fn test_bin_signable() {
let key_pair = ed25519::KeyPairFromSeed32Generator::generate(Seed32::new([
0u8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15,
]));
let signator = SignatorEnum::Ed25519(
key_pair
.generate_signator()
.expect("fail to generate signator !"),
);
let mut bin_signable_datas = BinSignableTestImpl {
datas: vec![0, 1, 2, 3],
issuer: PubKey::Ed25519(key_pair.pubkey),
sig: None,
};
assert_eq!(Err(SigError::NotSig), bin_signable_datas.verify());
let _bin_msg = bin_signable_datas
.sign(&signator)
.expect("Fail to sign datas !");
assert_eq!(
Err(SignError::AlreadySign),
bin_signable_datas.sign(&signator)
);
assert_eq!(Ok(()), bin_signable_datas.verify())
}
}
...@@ -48,7 +48,6 @@ ...@@ -48,7 +48,6 @@
//! `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/` //! `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`
//! with `=` as padding character. //! with `=` as padding character.
pub mod bin_signable;
pub mod ed25519; pub mod ed25519;
pub mod text_signable; pub mod text_signable;
......
...@@ -270,7 +270,7 @@ impl BlockchainModule { ...@@ -270,7 +270,7 @@ impl BlockchainModule {
} }
if let Some(_sync_opts) = sync_opts { if let Some(_sync_opts) = sync_opts {
// TODO ... // TODO HUGO...
// take into account sync options // take into account sync options
} else { } else {
// Start main loop // Start main loop
......
...@@ -10,8 +10,6 @@ edition = "2018" ...@@ -10,8 +10,6 @@ edition = "2018"
path = "lib.rs" path = "lib.rs"
[dependencies] [dependencies]
bincode = "1.0.*"
byteorder = "1.2.3"
dubp-common-doc = { path = "../../../dubp/common-doc"} #, version = "0.1.0" } dubp-common-doc = { path = "../../../dubp/common-doc"} #, version = "0.1.0" }
dubp-block-doc = { path = "../../../dubp/block-doc"} #, version = "0.1.0" } dubp-block-doc = { path = "../../../dubp/block-doc"} #, version = "0.1.0" }
dubp-currency-params = { path = "../../../dubp/currency-params" } dubp-currency-params = { path = "../../../dubp/currency-params" }
...@@ -21,11 +19,11 @@ durs-common-tools = { path = "../../../tools/common-tools" } ...@@ -21,11 +19,11 @@ durs-common-tools = { path = "../../../tools/common-tools" }
dup-crypto = { path = "../../../crypto" } dup-crypto = { path = "../../../crypto" }
failure = "0.1.5" failure = "0.1.5"
log = "0.4.*" log = "0.4.*"
serde = "1.0.*" pkstl = { path = "../../../tools/pkstl", features = ["bin","cbor"] }
serde_derive = "1.0.*" serde = { version = "1.0.*", features = ["derive"] }
serde_json = "1.0.*"
[dev-dependencies] [dev-dependencies]
bincode = "1.0.1"
pretty_assertions = "0.5.1" pretty_assertions = "0.5.1"
[features] [features]
...@@ -31,19 +31,13 @@ ...@@ -31,19 +31,13 @@
#[macro_use] #[macro_use]
extern crate pretty_assertions;*/ extern crate pretty_assertions;*/
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate log;
/// WS2Pv2 Messages /// WS2Pv2 Messages
pub mod v2; pub mod v2;
use crate::v2::WS2Pv2Message; use crate::v2::WS2Pv2Message;
use dup_crypto::hashs::Hash;
use dup_crypto::keys::bin_signable::BinSignable;
use dup_crypto::keys::*; use dup_crypto::keys::*;
use durs_common_tools::fatal_error; use pkstl::{IncomingMessage, SecureLayer};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)] #[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
/// WS2Pv2Message /// WS2Pv2Message
...@@ -59,88 +53,68 @@ pub enum WS2PMessage { ...@@ -59,88 +53,68 @@ pub enum WS2PMessage {
/// Enumerate errors can happen when parsing and checking messages /// Enumerate errors can happen when parsing and checking messages
#[derive(Debug)] #[derive(Debug)]
pub enum WS2PMessageError { pub enum WS2PMessageError {
/// Error at deserialization
DeserError(bincode::Error),
/// Invalid hash /// Invalid hash
InvalidHash, InvalidHash,
/// Secure transport layer error
SecureLayerError(pkstl::Error),
/// Invalid signature /// Invalid signature
SigError(SigError), SigError(SigError),
/// Unexpected empty message
UnexpectedEmpty,
} }
impl From<bincode::Error> for WS2PMessageError { impl From<pkstl::Error> for WS2PMessageError {
fn from(e: bincode::Error) -> Self { fn from(e: pkstl::Error) -> Self {
WS2PMessageError::DeserError(e) WS2PMessageError::SecureLayerError(e)
} }
} }
impl WS2PMessage { impl WS2PMessage {
/// Get signature length
pub fn sig_len(&self) -> usize {
match self.signature() {
None => 1, // 1 byte: option
Some(Sig::Ed25519(_)) => 69, // 1 byte: option, 4 bytes: algorithm, 64 bytes: signature
Some(Sig::Schnorr()) => fatal_error!("Schnorr algo not yet implemented !"),
}
}
/// Get message hash
pub fn hash(&self, bin_msg: &[u8]) -> Hash {
match *self {
WS2PMessage::V2(_) => Hash::compute(&bin_msg[0..(bin_msg.len() - self.sig_len())]),
WS2PMessage::_V0 | WS2PMessage::_V1 => {
fatal_error!("Dev error: must not use WS2PMessage version < 2 in WS2Pv2+ !")
}
}
}
/// Parse and check bin message /// Parse and check bin message
pub fn parse_and_check_bin_message(bin_msg: &[u8]) -> Result<WS2PMessage, WS2PMessageError> { pub fn parse_and_check_incoming_bin_message(
let msg: WS2PMessage = bincode::deserialize(&bin_msg)?; secure_transport_layer: &mut SecureLayer,
match msg.verify() { bin_msg: &[u8],
Ok(()) => Ok(msg), ) -> Result<(Vec<WS2PMessage>, Option<PubKey>), WS2PMessageError> {
Err(e) => Err(WS2PMessageError::SigError(e)), let incoming_msgs = secure_transport_layer.read::<WS2PMessage>(bin_msg)?;
}
} let mut incoming_ws2p_msgs = Vec::with_capacity(incoming_msgs.len());
} let mut remote_pubkey = None;
for incoming_msg in incoming_msgs {
impl<'de> BinSignable<'de> for WS2PMessage { match incoming_msg {
#[inline] IncomingMessage::Connect {
fn add_sig_to_bin_datas(&self, bin_datas: &mut Vec<u8>) { custom_datas: ws2p_msg_opt,
bin_datas.extend_from_slice( peer_sig_public_key,
&bincode::serialize(&self.signature()).expect("Fail to binarize sig !"), } => {
); if let Some(ws2p_msg) = ws2p_msg_opt {
} let mut pubkey_buffer = [0u8; 32];
#[inline] pubkey_buffer.copy_from_slice(&peer_sig_public_key[..]);
fn get_bin_without_sig(&self) -> Result<Vec<u8>, failure::Error> { remote_pubkey = Some(PubKey::Ed25519(ed25519::PublicKey(pubkey_buffer)));
let mut bin_msg = bincode::serialize(&self)?; incoming_ws2p_msgs.push(ws2p_msg);
let sig_size = bincode::serialized_size(&self.signature())?; } else {
let bin_msg_len = bin_msg.len(); return Err(WS2PMessageError::UnexpectedEmpty);
bin_msg.truncate(bin_msg_len - (sig_size as usize));
Ok(bin_msg)
}
fn issuer_pubkey(&self) -> PubKey {
match *self {
WS2PMessage::V2(ref msg_v2) => msg_v2.issuer_pubkey,
WS2PMessage::_V0 | WS2PMessage::_V1 => {
fatal_error!("Dev error: must not use WS2PMessage version < 2 in WS2Pv2+ !")
} }
} }
IncomingMessage::Ack {
custom_datas: ws2p_msg_opt,
} => {
if let Some(ws2p_msg) = ws2p_msg_opt {
incoming_ws2p_msgs.push(ws2p_msg);
} else {
return Err(WS2PMessageError::UnexpectedEmpty);
} }
fn signature(&self) -> Option<Sig> {
match *self {
WS2PMessage::V2(ref msg_v2) => msg_v2.signature,
WS2PMessage::_V0 | WS2PMessage::_V1 => {
fatal_error!("Dev error: must not use WS2PMessage version < 2 in WS2Pv2+ !")
} }
IncomingMessage::Message {
datas: ws2p_msg_opt,
} => {
if let Some(ws2p_msg) = ws2p_msg_opt {
incoming_ws2p_msgs.push(ws2p_msg);
} else {
return Err(WS2PMessageError::UnexpectedEmpty);
} }
} }
fn set_signature(&mut self, signature: Sig) {
match *self {
WS2PMessage::V2(ref mut msg_v2) => msg_v2.signature = Some(signature),
WS2PMessage::_V0 | WS2PMessage::_V1 => {
fatal_error!("Dev error: must not use WS2PMessage version < 2 in WS2Pv2+ !")
} }
} }
Ok((incoming_ws2p_msgs, remote_pubkey))
} }
} }
...@@ -154,7 +128,6 @@ mod tests { ...@@ -154,7 +128,6 @@ mod tests {
use dubp_common_doc::{BlockNumber, Blockstamp}; use dubp_common_doc::{BlockNumber, Blockstamp};
use dubp_currency_params::CurrencyName; use dubp_currency_params::CurrencyName;
use dubp_user_docs::documents::certification::*; use dubp_user_docs::documents::certification::*;
use dup_crypto::keys::bin_signable::BinSignable;
use dup_crypto::keys::*; use dup_crypto::keys::*;
use durs_network_documents::network_endpoint::*; use durs_network_documents::network_endpoint::*;
use durs_network_documents::network_peer::*; use durs_network_documents::network_peer::*;
...@@ -210,28 +183,14 @@ mod tests { ...@@ -210,28 +183,14 @@ mod tests {
} }
pub fn test_ws2p_message(payload: WS2Pv2MessagePayload) { pub fn test_ws2p_message(payload: WS2Pv2MessagePayload) {
let keypair1 = keypair1(); let ws2p_message = WS2PMessage::V2(WS2Pv2Message {
let signator =
SignatorEnum::Ed25519(keypair1.generate_signator().expect("fail to gen signator"));
let mut ws2p_message = WS2PMessage::V2(WS2Pv2Message {
currency_name: CurrencyName(String::from("g1")), currency_name: CurrencyName(String::from("g1")),
issuer_node_id: NodeId(0), issuer_node_id: NodeId(0),
issuer_pubkey: PubKey::Ed25519(keypair1.public_key()),
payload, payload,
signature: None,
}); });
let sign_result = ws2p_message.sign(&signator); // Test binarization and debinarization
if let Ok(bin_msg) = sign_result { let bin_msg = serialize(&ws2p_message).expect("Fail to serialize WS2Pv2Message !");
// Test binarization
assert_eq!(
serialize(&ws2p_message).expect("Fail to serialize WS2Pv2Message !"),
bin_msg
);
// Test sign
ws2p_message
.verify()
.expect("WS2Pv2Message : Invalid signature !");
// Test debinarization // Test debinarization
let debinarization_result: Result<WS2PMessage, bincode::Error> = deserialize(&bin_msg); let debinarization_result: Result<WS2PMessage, bincode::Error> = deserialize(&bin_msg);
if let Ok(ws2p_message2) = debinarization_result { if let Ok(ws2p_message2) = debinarization_result {
...@@ -242,12 +201,6 @@ mod tests { ...@@ -242,12 +201,6 @@ mod tests {
debinarization_result.err().unwrap() debinarization_result.err().unwrap()
); );
} }
} else {
panic!(
"Fail to sign ws2p_message : {:?}",
sign_result.err().unwrap()
);
}
} }
pub fn create_cert_doc() -> CompactCertificationDocumentV10 { pub fn create_cert_doc() -> CompactCertificationDocumentV10 {
......
...@@ -13,6 +13,8 @@ ...@@ -13,6 +13,8 @@
// You should have received a copy of the GNU Affero General Public License // You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>. // along with this program. If not, see <https://www.gnu.org/licenses/>.
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)] #[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
/// WS2PFeatures /// WS2PFeatures
pub struct WS2PFeatures(pub [u8; 4]); pub struct WS2PFeatures(pub [u8; 4]);
......
...@@ -18,6 +18,7 @@ use super::api_features::WS2PFeatures; ...@@ -18,6 +18,7 @@ use super::api_features::WS2PFeatures;
use dubp_common_doc::blockstamp::Blockstamp; use dubp_common_doc::blockstamp::Blockstamp;
use dup_crypto::hashs::Hash; use dup_crypto::hashs::Hash;
use durs_network_documents::network_peer::PeerCardV11; use durs_network_documents::network_peer::PeerCardV11;
use serde::{Deserialize, Serialize};
/// WS2P v2 connect message min size /// WS2P v2 connect message min size
pub static CONNECT_MSG_MIN_SIZE: &usize = &36; pub static CONNECT_MSG_MIN_SIZE: &usize = &36;
...@@ -31,7 +32,7 @@ pub enum WS2Pv2ConnectType { ...@@ -31,7 +32,7 @@ pub enum WS2Pv2ConnectType {
OutgoingClient, OutgoingClient,
/// Server outgoing connection /// Server outgoing connection
OutgoingServer, OutgoingServer,
/// Sync connection (from blockstamp, or from genesis block if blockstamp is none) /// Sync outgoing connection (from blockstamp, or from genesis block if blockstamp is none)
Sync { Sync {
/// block from which the sync should start /// block from which the sync should start
from_blockstamp: Option<Blockstamp>, from_blockstamp: Option<Blockstamp>,
...@@ -105,6 +106,7 @@ mod tests { ...@@ -105,6 +106,7 @@ mod tests {
use crate::tests::*; use crate::tests::*;
use dubp_common_doc::Blockstamp; use dubp_common_doc::Blockstamp;
use dup_crypto::keys::text_signable::TextSignable; use dup_crypto::keys::text_signable::TextSignable;
use dup_crypto::keys::*;
#[test] #[test]
fn test_ws2p_message_connect() { fn test_ws2p_message_connect() {
......
...@@ -33,9 +33,9 @@ pub mod sync_info; ...@@ -33,9 +33,9 @@ pub mod sync_info;
use crate::v2::payload_container::*; use crate::v2::payload_container::*;
use crate::WS2PMessage; use crate::WS2PMessage;
use dubp_currency_params::CurrencyName; use dubp_currency_params::CurrencyName;
use dup_crypto::keys::bin_signable::BinSignable;
use dup_crypto::keys::*;
use durs_network_documents::NodeId; use durs_network_documents::NodeId;
use serde::{Deserialize, Serialize};
use std::io::BufWriter;
/// WS2P v2 message metadata size /// WS2P v2 message metadata size
pub static WS2P_V2_MESSAGE_METADATA_SIZE: &usize = &144; pub static WS2P_V2_MESSAGE_METADATA_SIZE: &usize = &144;
...@@ -47,12 +47,8 @@ pub struct WS2Pv2Message { ...@@ -47,12 +47,8 @@ pub struct WS2Pv2Message {
pub currency_name: CurrencyName, pub currency_name: CurrencyName,
/// Issuer NodeId /// Issuer NodeId
pub issuer_node_id: NodeId, pub issuer_node_id: NodeId,
/// Issuer plublic key
pub issuer_pubkey: PubKey,
/// Message payload /// Message payload
pub payload: WS2Pv2MessagePayload, pub payload: WS2Pv2MessagePayload,
/// Signature
pub signature: Option<Sig>,
} }
impl WS2Pv2Message { impl WS2Pv2Message {
...@@ -61,21 +57,48 @@ impl WS2Pv2Message { ...@@ -61,21 +57,48 @@ impl WS2Pv2Message {
/// Encapsulate message payload /// Encapsulate message payload
pub fn encapsulate_payload( pub fn encapsulate_payload(
sl: &mut pkstl::SecureLayer,
currency_name: CurrencyName, currency_name: CurrencyName,
issuer_node_id: NodeId, issuer_node_id: NodeId,
issuer_signator: &SignatorEnum,
payload: WS2Pv2MessagePayload, payload: WS2Pv2MessagePayload,
) -> Result<(WS2PMessage, Vec<u8>), SignError> { ) -> Result<Vec<u8>, pkstl::Error> {
let mut msg = WS2PMessage::V2(WS2Pv2Message { match payload {
WS2Pv2MessagePayload::Connect(_) => {
let msg = WS2PMessage::V2(WS2Pv2Message {
currency_name, currency_name,
issuer_node_id, issuer_node_id,
issuer_pubkey: issuer_signator.public_key(),
payload, payload,
signature: None,
}); });
match msg.sign(issuer_signator) { let mut buffer = BufWriter::new(Vec::with_capacity(1_024));
Ok(bin_msg) => Ok((msg, bin_msg)), sl.write_connect_msg(Some(&msg), &mut buffer)?;
Err(e) => Err(e), Ok(buffer
.into_inner()
.expect("Vec buffer must be always flushed"))
}
WS2Pv2MessagePayload::Ack { .. } => {
let msg = WS2PMessage::V2(WS2Pv2Message {
currency_name,
issuer_node_id,
payload,
});
let mut buffer = BufWriter::new(Vec::with_capacity(1_024));
sl.write_ack_msg(Some(&msg), &mut buffer)?;
Ok(buffer
.into_inner()
.expect("Vec buffer must be always flushed"))
}
_ => {
let msg = WS2PMessage::V2(WS2Pv2Message {
currency_name,
issuer_node_id,
payload,
});
let mut buffer = BufWriter::new(Vec::with_capacity(1_024));
sl.write(&msg, &mut buffer)?;
Ok(buffer
.into_inner()
.expect("Vec buffer must be always flushed"))
}
} }
} }
} }
...@@ -86,6 +109,7 @@ mod tests { ...@@ -86,6 +109,7 @@ mod tests {
use crate::tests::*; use crate::tests::*;
use dup_crypto::hashs::Hash; use dup_crypto::hashs::Hash;
use dup_crypto::keys::text_signable::TextSignable; use dup_crypto::keys::text_signable::TextSignable;
use dup_crypto::keys::*;
#[test] #[test]
fn test_ws2p_message_ack() { fn test_ws2p_message_ack() {
......
...@@ -13,6 +13,7 @@ ...@@ -13,6 +13,7 @@
// You should have received a copy of the GNU Affero General Public License // You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>. // along with this program. If not, see <https://www.gnu.org/licenses/>.
use serde::{Deserialize, Serialize};
use std::num::NonZeroU16; use std::num::NonZeroU16;
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)] #[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
......
...@@ -29,6 +29,7 @@ use dup_crypto::hashs::Hash; ...@@ -29,6 +29,7 @@ use dup_crypto::hashs::Hash;
use durs_network_documents::network_head_v2::NetworkHeadV2; use durs_network_documents::network_head_v2::NetworkHeadV2;
use durs_network_documents::network_head_v3::NetworkHeadV3; use durs_network_documents::network_head_v3::NetworkHeadV3;
use durs_network_documents::network_peer::PeerCardV11; use durs_network_documents::network_peer::PeerCardV11;
use serde::{Deserialize, Serialize};
/// WS2P v2 message payload metadata size /// WS2P v2 message payload metadata size
pub static WS2P_V2_MESSAGE_PAYLOAD_METADATA_SIZE: &usize = &8; pub static WS2P_V2_MESSAGE_PAYLOAD_METADATA_SIZE: &usize = &8;
......
...@@ -19,6 +19,7 @@ use dubp_user_docs::documents::certification::CompactCertificationDocumentV10; ...@@ -19,6 +19,7 @@ use dubp_user_docs::documents::certification::CompactCertificationDocumentV10;
use dubp_user_docs::documents::identity::v10::CompactIdentityDocumentV10; use dubp_user_docs::documents::identity::v10::CompactIdentityDocumentV10;
use dubp_user_docs::documents::membership::v10::CompactPoolMembershipDoc; use dubp_user_docs::documents::membership::v10::CompactPoolMembershipDoc;
use dup_crypto::hashs::Hash; use dup_crypto::hashs::Hash;
use serde::{Deserialize, Serialize};
use std::str; use std::str;
/// WS2Pv2 request response /// WS2Pv2 request response
......
...@@ -15,6 +15,7 @@ ...@@ -15,6 +15,7 @@
use dubp_common_doc::blockstamp::Blockstamp; use dubp_common_doc::blockstamp::Blockstamp;
use dubp_common_doc::BlockNumber; use dubp_common_doc::BlockNumber;
use serde::{Deserialize, Serialize};
/// WS2Pv2Request /// WS2Pv2Request
#[derive(Debug, Copy, Clone, Eq, PartialEq, Serialize, Deserialize)] #[derive(Debug, Copy, Clone, Eq, PartialEq, Serialize, Deserialize)]
......
...@@ -14,6 +14,7 @@ ...@@ -14,6 +14,7 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>. // along with this program. If not, see <https://www.gnu.org/licenses/>.
use dup_crypto::keys::*; use dup_crypto::keys::*;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
/// WS2Pv2SecretFlags /// WS2Pv2SecretFlags
......
...@@ -17,6 +17,7 @@ ...@@ -17,6 +17,7 @@
use dubp_common_doc::BlockHash; use dubp_common_doc::BlockHash;
use dubp_common_doc::Blockstamp; use dubp_common_doc::Blockstamp;
use durs_network_documents::network_peer::PeerCard; use durs_network_documents::network_peer::PeerCard;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] // Copy #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] // Copy
/// WS2Pv2SyncInfo /// WS2Pv2SyncInfo
......
...@@ -25,10 +25,10 @@ durs-message= { path = "../../../core/message" } ...@@ -25,10 +25,10 @@ durs-message= { path = "../../../core/message" }
durs-network= { path = "../../../core/network" } durs-network= { path = "../../../core/network" }
failure = "0.1.5" failure = "0.1.5"
log = "0.4.*" log = "0.4.*"
pkstl = { path = "../../../tools/pkstl", features = ["bin","cbor"] }
serde = "1.0.*" serde = "1.0.*"
serde_derive = "1.0.*" serde_derive = "1.0.*"
unwrap = "1.2.1" unwrap = "1.2.1"
maplit = "1.0.1"
[dev-dependencies] [dev-dependencies]
pretty_assertions = "0.5.1" pretty_assertions = "0.5.1"
......
...@@ -31,22 +31,22 @@ pub static WS2P_SPAM_LIMIT: &usize = &6; ...@@ -31,22 +31,22 @@ pub static WS2P_SPAM_LIMIT: &usize = &6;
pub static WS2P_SPAM_SLEEP_TIME_IN_SEC: &u64 = &100; pub static WS2P_SPAM_SLEEP_TIME_IN_SEC: &u64 = &100;
/// Number of invalid messages tolerated /// Number of invalid messages tolerated
pub static WS2P_INVALID_MSGS_LIMIT: &'static usize = &5; pub static WS2P_INVALID_MSGS_LIMIT: &usize = &5;
/// Number of simultaneous outgoing connection /// Number of simultaneous outgoing connection
pub static WS2P_DEFAULT_OUTCOMING_QUOTA: &'static usize = &10; pub static WS2P_DEFAULT_OUTCOMING_QUOTA: &usize = &10;
/*pub static WS2P_OUTCOMING_INTERVAL_AT_STARTUP: &'static u64 = &75; /*pub static WS2P_OUTCOMING_INTERVAL_AT_STARTUP: &u64 = &75;
pub static WS2P_OUTCOMING_INTERVAL: &'static u64 = &300;*/ pub static WS2P_OUTCOMING_INTERVAL: &u64 = &300;*/
/// Timeout before receiving message from service /// Timeout before receiving message from service
pub static WS2P_RECV_SERVICE_FREQ_IN_MS: &'static u64 = &1_000; pub static WS2P_RECV_SERVICE_FREQ_IN_MS: &u64 = &1_000;
/* /*
pub static WS2P_REQUEST_TIMEOUT: &'static u64 = &30_000; pub static WS2P_REQUEST_TIMEOUT: &u64 = &30_000;
pub static DURATION_BEFORE_RECORDING_ENDPOINT: &'static u64 = &180; pub static DURATION_BEFORE_RECORDING_ENDPOINT: &u64 = &180;
pub static BLOCKS_REQUEST_INTERVAL: &'static u64 = &60; pub static BLOCKS_REQUEST_INTERVAL: &u64 = &60;
pub static PENDING_IDENTITIES_REQUEST_INTERVAL: &'static u64 = &40; pub static PENDING_IDENTITIES_REQUEST_INTERVAL: &u64 = &40;
*/ */
/// Chunk size (in blocks), can differ with blockchain chunk size /// Chunk size (in blocks), can differ with blockchain chunk size
pub static CHUNK_SIZE: &'static u32 = &500; pub static CHUNK_SIZE: &u32 = &500;
...@@ -25,12 +25,13 @@ use crate::connection_state::WS2PConnectionState; ...@@ -25,12 +25,13 @@ use crate::connection_state::WS2PConnectionState;
use crate::constants; use crate::constants;
use crate::orchestrator::OrchestratorMsg; use crate::orchestrator::OrchestratorMsg;
use crate::websocket::{WebsocketAction, WebsocketIncomingEvent}; use crate::websocket::{WebsocketAction, WebsocketIncomingEvent};
use dup_crypto::keys::*;
use durs_module::ModuleMessage; use durs_module::ModuleMessage;
use durs_network_documents::NodeFullId; use durs_network_documents::NodeFullId;
use durs_ws2p_messages::v2::connect::WS2Pv2ConnectType; use durs_ws2p_messages::v2::connect::WS2Pv2ConnectType;
use durs_ws2p_messages::WS2PMessage; use durs_ws2p_messages::WS2PMessage;
use failure::Fail; use failure::Fail;
use std::sync::mpsc::{Receiver, SendError, Sender}; use std::sync::mpsc::{Receiver, Sender};
use std::time::SystemTime; use std::time::SystemTime;
use unwrap::unwrap; use unwrap::unwrap;
...@@ -66,7 +67,7 @@ impl WS2PControllerId { ...@@ -66,7 +67,7 @@ impl WS2PControllerId {
} }
} }
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug)]
/// Event transmitted to the orchestrator /// Event transmitted to the orchestrator
pub enum WS2PControllerEvent { pub enum WS2PControllerEvent {
/// New connection established /// New connection established
...@@ -75,6 +76,8 @@ pub enum WS2PControllerEvent { ...@@ -75,6 +76,8 @@ pub enum WS2PControllerEvent {
conn_type: WS2Pv2ConnectType, conn_type: WS2Pv2ConnectType,
/// Remote node full id /// Remote node full id
remote_full_id: NodeFullId, remote_full_id: NodeFullId,
/// Connection secure layer
secure_layer: pkstl::SecureLayer,
}, },
/// Connection state change /// Connection state change
StateChange { StateChange {
...@@ -89,8 +92,8 @@ pub enum WS2PControllerEvent { ...@@ -89,8 +92,8 @@ pub enum WS2PControllerEvent {
}, },
} }
#[derive(Debug)]
/// WS2P Controller /// WS2P Controller
#[derive(Debug)]
pub struct WS2PController<M: ModuleMessage> { pub struct WS2PController<M: ModuleMessage> {
/// Controller id /// Controller id
pub id: WS2PControllerId, pub id: WS2PControllerId,
...@@ -100,14 +103,28 @@ pub struct WS2PController<M: ModuleMessage> { ...@@ -100,14 +103,28 @@ pub struct WS2PController<M: ModuleMessage> {
pub meta_datas: WS2PControllerMetaDatas, pub meta_datas: WS2PControllerMetaDatas,
/// Controller receiver /// Controller receiver
pub receiver: Receiver<WebsocketActionOrder>, pub receiver: Receiver<WebsocketActionOrder>,
/// Connection Security Layer
pub secure_layer: pkstl::SecureLayer,
} }
#[derive(Copy, Clone, Debug, Fail)] #[derive(Debug, Fail)]
/// WS2P Controller process error /// WS2P Controller process error
pub enum WS2PControllerProcessError { pub enum WS2PControllerProcessError {
/// Orchestrator unreacheable /// Orchestrator unreacheable
#[fail(display = "WS2P Orchestrator unreachable")] #[fail(display = "WS2P Orchestrator unreachable")]
OrchestratorUnreacheable, OrchestratorUnreacheable,
/// Receive connect message without public key
#[fail(display = "Receive connect message without public key")]
ReceiveConnectMsgWithoutPubKey,
/// Security error
#[fail(display = "Security error: {:?}", _0)]
SecurityError(pkstl::Error),
}
impl From<pkstl::Error> for WS2PControllerProcessError {
fn from(e: pkstl::Error) -> Self {
WS2PControllerProcessError::SecurityError(e)
}
} }
/// Websocket action order /// Websocket action order
...@@ -177,16 +194,35 @@ impl<M: ModuleMessage> WS2PController<M> { ...@@ -177,16 +194,35 @@ impl<M: ModuleMessage> WS2PController<M> {
id: WS2PControllerId, id: WS2PControllerId,
meta_datas: WS2PControllerMetaDatas, meta_datas: WS2PControllerMetaDatas,
orchestrator_sender: Sender<OrchestratorMsg<M>>, orchestrator_sender: Sender<OrchestratorMsg<M>>,
) -> Result<WS2PController<M>, SendError<OrchestratorMsg<M>>> { ) -> Result<WS2PController<M>, WS2PControllerProcessError> {
let (sender, receiver) = std::sync::mpsc::channel(); let (sender, receiver) = std::sync::mpsc::channel();
orchestrator_sender.send(OrchestratorMsg::ControllerSender { id, sender })?; orchestrator_sender
.send(OrchestratorMsg::ControllerSender { id, sender })
.map_err(|_| WS2PControllerProcessError::OrchestratorUnreacheable)?;
let mut my_key_pair_seed_buffer = [0u8; 32];
my_key_pair_seed_buffer.copy_from_slice(meta_datas.local_node.my_key_pair.seed().as_ref());
let secure_layer = pkstl::SecureLayer::create(
pkstl::SecureLayerConfig {
message_format: pkstl::MessageFormat::Cbor,
..pkstl::SecureLayerConfig::default()
},
Some(pkstl::Seed32::new(my_key_pair_seed_buffer)),
if let Some(ref remote_node) = meta_datas.remote_node {
Some(remote_node.remote_full_id.1.to_bytes_vector())
} else {
None
},
)?;
Ok(WS2PController { Ok(WS2PController {
id, id,
meta_datas, meta_datas,
orchestrator_sender, orchestrator_sender,
receiver, receiver,
secure_layer,
}) })
} }
...@@ -205,7 +241,7 @@ impl<M: ModuleMessage> WS2PController<M> { ...@@ -205,7 +241,7 @@ impl<M: ModuleMessage> WS2PController<M> {
pub fn process( pub fn process(
&mut self, &mut self,
event: WebsocketIncomingEvent, event: WebsocketIncomingEvent,
) -> Result<Option<WebsocketActionOrder>, WS2PControllerProcessError> { ) -> Result<Vec<WebsocketActionOrder>, WS2PControllerProcessError> {
match event { match event {
WebsocketIncomingEvent::OnOpen { remote_addr } => on_open::process(self, remote_addr), WebsocketIncomingEvent::OnOpen { remote_addr } => on_open::process(self, remote_addr),
WebsocketIncomingEvent::OnMessage { msg } => on_message::process(self, msg), WebsocketIncomingEvent::OnMessage { msg } => on_message::process(self, msg),
...@@ -222,7 +258,7 @@ impl<M: ModuleMessage> WS2PController<M> { ...@@ -222,7 +258,7 @@ impl<M: ModuleMessage> WS2PController<M> {
reason.unwrap_or_else(|| "".to_owned()) reason.unwrap_or_else(|| "".to_owned())
); );
self.update_conn_state(WS2PConnectionState::Close)?; self.update_conn_state(WS2PConnectionState::Close)?;
Ok(None) Ok(vec![])
} }
} }
} }
......
...@@ -38,7 +38,7 @@ use std::time::{Duration, SystemTime}; ...@@ -38,7 +38,7 @@ use std::time::{Duration, SystemTime};
pub fn process<M: ModuleMessage>( pub fn process<M: ModuleMessage>(
controller: &mut WS2PController<M>, controller: &mut WS2PController<M>,
msg: WebsocketMessage, msg: WebsocketMessage,
) -> Result<Option<WebsocketActionOrder>, WS2PControllerProcessError> { ) -> Result<Vec<WebsocketActionOrder>, WS2PControllerProcessError> {
// Update last_mess_time // Update last_mess_time
controller.meta_datas.last_mess_time = SystemTime::now(); controller.meta_datas.last_mess_time = SystemTime::now();
...@@ -64,67 +64,90 @@ pub fn process<M: ModuleMessage>( ...@@ -64,67 +64,90 @@ pub fn process<M: ModuleMessage>(
*constants::WS2P_SPAM_SLEEP_TIME_IN_SEC, *constants::WS2P_SPAM_SLEEP_TIME_IN_SEC,
)); ));
controller.meta_datas.last_mess_time = SystemTime::now(); controller.meta_datas.last_mess_time = SystemTime::now();
return Ok(None); return Ok(vec![]);
} }
if let WebsocketMessage::Bin(bin_msg) = msg { if let WebsocketMessage::Bin(bin_msg) = msg {
log::debug!("Receive new bin message there is not a spam !"); log::debug!("Receive new bin message there is not a spam !");
match WS2PMessage::parse_and_check_bin_message(&bin_msg) { match WS2PMessage::parse_and_check_incoming_bin_message(
Ok(valid_msg) => match valid_msg { &mut controller.secure_layer,
WS2PMessage::V2(ref msg_v2) => { &bin_msg,
match msg_v2.payload { ) {
Ok((valid_msgs, remote_pubkey_opt)) => {
let mut orders: Vec<WebsocketActionOrder> = Vec::new();
for valid_msg in valid_msgs {
match valid_msg {
WS2PMessage::V2(ref msg_v2) => match msg_v2.payload {
WS2Pv2MessagePayload::Connect(ref box_connect_msg) => { WS2Pv2MessagePayload::Connect(ref box_connect_msg) => {
let connect_msg = box_connect_msg.deref(); let connect_msg = box_connect_msg.deref();
// Get remote node id // Get remote node id
let remote_full_id = let remote_full_id = if let Some(remote_pubkey) = remote_pubkey_opt
NodeFullId(msg_v2.issuer_node_id, msg_v2.issuer_pubkey); {
NodeFullId(msg_v2.issuer_node_id, remote_pubkey)
} else {
return Err(
WS2PControllerProcessError::ReceiveConnectMsgWithoutPubKey,
);
};
// Process connect message // Process connect message
connect_msg::process_ws2p_v2p_connect_msg( orders.append(&mut connect_msg::process_ws2p_v2p_connect_msg(
controller, controller,
remote_full_id, remote_full_id,
connect_msg, connect_msg,
) )?);
} }
WS2Pv2MessagePayload::Ack { WS2Pv2MessagePayload::Ack {
challenge: ack_msg_challenge, challenge: ack_msg_challenge,
} => { } => {
// Process ack message // Process ack message
ack_msg::process_ws2p_v2p_ack_msg(controller, ack_msg_challenge) orders.append(&mut ack_msg::process_ws2p_v2p_ack_msg(
controller,
ack_msg_challenge,
)?);
} }
WS2Pv2MessagePayload::SecretFlags(ref secret_flags) => { WS2Pv2MessagePayload::SecretFlags(ref secret_flags) => {
secret_flags::process_ws2p_v2p_secret_flags_msg( // Process secret flags
orders.append(
&mut secret_flags::process_ws2p_v2p_secret_flags_msg(
controller, controller,
secret_flags, secret_flags,
) )?,
);
} }
WS2Pv2MessagePayload::Ok(_) => { WS2Pv2MessagePayload::Ok(_) => {
// Process ok message // Process ok message
ok_msg::process_ws2p_v2p_ok_msg(controller) orders.append(&mut ok_msg::process_ws2p_v2p_ok_msg(controller)?);
} }
WS2Pv2MessagePayload::Ko(_) => Ok(close_with_reason( WS2Pv2MessagePayload::Ko(_) => {
return Ok(close_with_reason(
"Receive Ko message !", "Receive Ko message !",
WS2PConnectionState::Denial, WS2PConnectionState::Denial,
)), ))
}
_ => { _ => {
if let WS2PConnectionState::Established = controller.meta_datas.state { if let WS2PConnectionState::Established =
controller controller.meta_datas.state
.send_event(WS2PControllerEvent::RecvValidMsg { {
controller.send_event(WS2PControllerEvent::RecvValidMsg {
ws2p_msg: valid_msg, ws2p_msg: valid_msg,
}) })?;
.map(|_| None)
} else { } else {
Ok(close_with_reason( return Ok(close_with_reason(
"Receive datas message on negociation !", "Receive datas message on negociation !",
WS2PConnectionState::Denial, WS2PConnectionState::Denial,
)) ));
} }
} }
},
WS2PMessage::_V0 | WS2PMessage::_V1 => fatal_error!(
"Dev error: must not use WS2PMessage version < 2 in WS2Pv2+ !"
),
} }
} }
WS2PMessage::_V0 | WS2PMessage::_V1 => { Ok(orders)
fatal_error!("Dev error: must not use WS2PMessage version < 2 in WS2Pv2+ !")
} }
},
Err(ws2p_msg_err) => { Err(ws2p_msg_err) => {
log::warn!("Message is invalid : {:?}", ws2p_msg_err); log::warn!("Message is invalid : {:?}", ws2p_msg_err);
controller.meta_datas.count_invalid_msgs += 1; controller.meta_datas.count_invalid_msgs += 1;
...@@ -134,7 +157,7 @@ pub fn process<M: ModuleMessage>( ...@@ -134,7 +157,7 @@ pub fn process<M: ModuleMessage>(
WS2PConnectionState::Denial, WS2PConnectionState::Denial,
)) ))
} else { } else {
Ok(None) Ok(vec![])
} }
} }
} }
...@@ -146,12 +169,12 @@ pub fn process<M: ModuleMessage>( ...@@ -146,12 +169,12 @@ pub fn process<M: ModuleMessage>(
} }
} }
fn close_with_reason(reason: &str, new_state: WS2PConnectionState) -> Option<WebsocketActionOrder> { fn close_with_reason(reason: &str, new_state: WS2PConnectionState) -> Vec<WebsocketActionOrder> {
Some(WebsocketActionOrder { vec![WebsocketActionOrder {
ws_action: WebsocketAction::CloseConnection { ws_action: WebsocketAction::CloseConnection {
reason: Some(reason.to_owned()), reason: Some(reason.to_owned()),
}, },
new_state_if_success: Some(new_state), new_state_if_success: Some(new_state),
new_state_if_fail: new_state, new_state_if_fail: new_state,
}) }]
} }
...@@ -30,7 +30,7 @@ use log::error; ...@@ -30,7 +30,7 @@ use log::error;
pub fn process_ws2p_v2p_ack_msg<M: ModuleMessage>( pub fn process_ws2p_v2p_ack_msg<M: ModuleMessage>(
controller: &mut WS2PController<M>, // controller contains original challenge controller: &mut WS2PController<M>, // controller contains original challenge
ack_msg_challenge: Hash, ack_msg_challenge: Hash,
) -> Result<Option<WebsocketActionOrder>, WS2PControllerProcessError> { ) -> Result<Vec<WebsocketActionOrder>, WS2PControllerProcessError> {
log::debug!("Receive ACK message !"); log::debug!("Receive ACK message !");
match controller.meta_datas.state { match controller.meta_datas.state {
...@@ -59,13 +59,13 @@ fn process<M: ModuleMessage>( ...@@ -59,13 +59,13 @@ fn process<M: ModuleMessage>(
controller: &mut WS2PController<M>, controller: &mut WS2PController<M>,
ack_msg_challenge: Hash, ack_msg_challenge: Hash,
success_status: WS2PConnectionState, success_status: WS2PConnectionState,
) -> Result<Option<WebsocketActionOrder>, WS2PControllerProcessError> { ) -> Result<Vec<WebsocketActionOrder>, WS2PControllerProcessError> {
if controller.meta_datas.challenge != ack_msg_challenge { if controller.meta_datas.challenge != ack_msg_challenge {
controller controller
.update_conn_state(WS2PConnectionState::Denial) .update_conn_state(WS2PConnectionState::Denial)
.map(|_| None) .map(|_| vec![])
} else { } else {
Ok(Some(send_ok_msg(controller, success_status))) Ok(vec![send_ok_msg(controller, success_status)])
} }
} }
...@@ -78,10 +78,10 @@ fn send_ok_msg<M: ModuleMessage>( ...@@ -78,10 +78,10 @@ fn send_ok_msg<M: ModuleMessage>(
let ok_msg = WS2Pv2OkMsg::default(); let ok_msg = WS2Pv2OkMsg::default();
// Encapsulate and binarize OK message // Encapsulate and binarize OK message
if let Ok((_, bin_ok_msg)) = WS2Pv2Message::encapsulate_payload( if let Ok(bin_ok_msg) = WS2Pv2Message::encapsulate_payload(
&mut controller.secure_layer,
controller.meta_datas.currency.clone(), controller.meta_datas.currency.clone(),
controller.meta_datas.local_node.my_node_id, controller.meta_datas.local_node.my_node_id,
&controller.meta_datas.signator,
WS2Pv2MessagePayload::Ok(ok_msg), WS2Pv2MessagePayload::Ok(ok_msg),
) { ) {
// Order the sending of a OK message // Order the sending of a OK message
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment