Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 2 additions & 5 deletions adapter/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@
#![deny(clippy::match_bool)]

use primitives::{Address, BigNum};
use thiserror::Error;
use tiny_keccak::Keccak;
use web3::{
ethabi::{encode, token::Token},
types::{Address as EthAddress, U256},
};
use thiserror::Error;

pub use self::dummy::DummyAdapter;
pub use self::ethereum::EthereumAdapter;
Expand All @@ -25,10 +25,7 @@ pub enum AdapterTypes {
#[error("{0}")]
pub struct BalanceLeafError(String);

pub fn get_signable_state_root(
channel_id: &[u8],
balance_root: &[u8; 32],
) -> [u8; 32] {
pub fn get_signable_state_root(channel_id: &[u8], balance_root: &[u8; 32]) -> [u8; 32] {
let tokens = [
Token::FixedBytes(channel_id.to_vec()),
Token::FixedBytes(balance_root.to_vec()),
Expand Down
7 changes: 1 addition & 6 deletions primitives/src/adapter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,7 @@ use std::{collections::HashMap, convert::From, fmt};
pub type AdapterResult<T, AE> = Result<T, Error<AE>>;

pub trait AdapterErrorKind: fmt::Debug + fmt::Display {}

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Deposit {
pub total: BigNum,
pub still_on_create2: BigNum,
}
pub type Deposit = crate::Deposit<BigNum>;

#[derive(Debug)]
pub enum Error<AE: AdapterErrorKind> {
Expand Down
4 changes: 3 additions & 1 deletion primitives/src/campaign.rs
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,8 @@ pub mod validators {

#[cfg(feature = "postgres")]
mod postgres {
use crate::channel_v5::Channel;

use super::{Active, Campaign, CampaignId, PricingBounds, Validators};
use bytes::BytesMut;
use postgres_types::{accepts, to_sql_checked, FromSql, IsNull, Json, ToSql, Type};
Expand All @@ -368,7 +370,7 @@ mod postgres {
fn from(row: &Row) -> Self {
Self {
id: row.get("id"),
channel: row.get("channel"),
channel: Channel::from(row),
creator: row.get("creator"),
budget: row.get("budget"),
validators: row.get("validators"),
Expand Down
4 changes: 4 additions & 0 deletions primitives/src/channel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ impl FromStr for ChannelId {

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
#[deprecated = "This is the old V4 Channel"]
pub struct Channel {
pub id: ChannelId,
pub creator: ValidatorId,
Expand Down Expand Up @@ -161,6 +162,7 @@ impl PricingBounds {

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
#[deprecated = "This is the old V4 Channel Spec"]
pub struct ChannelSpec {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub title: Option<String>,
Expand Down Expand Up @@ -206,9 +208,11 @@ pub struct ChannelSpec {

#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
/// A (leader, follower) tuple
#[deprecated = "This is the old V4 Channel ValidatorSpecs"]
pub struct SpecValidators(ValidatorDesc, ValidatorDesc);

#[derive(Debug)]
#[deprecated = "This is the old V4 Channel ValidatorSpecs"]
pub enum SpecValidator<'a> {
Leader(&'a ValidatorDesc),
Follower(&'a ValidatorDesc),
Expand Down
63 changes: 38 additions & 25 deletions primitives/src/channel_v5.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,65 +127,78 @@ mod test {

#[cfg(feature = "postgres")]
mod postgres {
use super::Channel;
use super::{Channel, Nonce};
use bytes::BytesMut;
use postgres_types::{accepts, to_sql_checked, FromSql, IsNull, Json, ToSql, Type};
use postgres_types::{accepts, to_sql_checked, FromSql, IsNull, ToSql, Type};
use std::error::Error;
use tokio_postgres::Row;

impl<'a> FromSql<'a> for Channel {
impl<'a> FromSql<'a> for Nonce {
fn from_sql(ty: &Type, raw: &'a [u8]) -> Result<Self, Box<dyn Error + Sync + Send>> {
let json: Json<Channel> = FromSql::from_sql(ty, raw)?;
let nonce_string = String::from_sql(ty, raw)?;

Ok(json.0)
Ok(serde_json::from_value(serde_json::Value::String(
nonce_string,
))?)
}

accepts!(JSONB);
accepts!(VARCHAR);
}

impl ToSql for Channel {
impl ToSql for Nonce {
fn to_sql(
&self,
ty: &Type,
w: &mut BytesMut,
) -> Result<IsNull, Box<dyn Error + Sync + Send>> {
Json(self).to_sql(ty, w)
self.0.to_string().to_sql(ty, w)
}

accepts!(JSONB);
accepts!(VARCHAR);
to_sql_checked!();
}

impl From<&Row> for Channel {
fn from(row: &Row) -> Self {
Self {
leader: row.get("leader"),
follower: row.get("follower"),
guardian: row.get("guardian"),
token: row.get("token"),
nonce: row.get("nonce"),
}
}
}

#[cfg(test)]
mod test {
use crate::util::tests::prep_db::{postgres::POSTGRES_POOL, DUMMY_CAMPAIGN};
use crate::{channel_v5::Nonce, util::tests::prep_db::postgres::POSTGRES_POOL};
#[tokio::test]
async fn channel_to_from_sql() {
async fn nonce_to_from_sql() {
let client = POSTGRES_POOL.get().await.unwrap();

let channel = DUMMY_CAMPAIGN.channel.clone();
let sql_type = "JSONB";
let nonce = Nonce::from(123_456_789_u64);
let sql_type = "VARCHAR";

// from SQL
{
let channel_json = serde_json::to_string(&channel).expect("Should serialize");

let rows = client
.query(&*format!("SELECT '{}'::{}", channel_json, sql_type), &[])
let row_nonce = client
.query_one(&*format!("SELECT '{}'::{}", nonce, sql_type), &[])
.await
.unwrap();
let result = rows[0].get(0);
.unwrap()
.get(0);

assert_eq!(&channel, &result);
assert_eq!(&nonce, &row_nonce);
}

// to SQL
{
let rows = client
.query(&*format!("SELECT $1::{}", sql_type), &[&channel])
let row_nonce = client
.query_one(&*format!("SELECT $1::{}", sql_type), &[&nonce])
.await
.unwrap();
let result = rows[0].get(0);
assert_eq!(&channel, &result);
.unwrap()
.get(0);
assert_eq!(&nonce, &row_nonce);
}
}
}
Expand Down
42 changes: 41 additions & 1 deletion primitives/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#![deny(rust_2018_idioms)]
#![deny(clippy::all)]
#![allow(deprecated)]
use std::{error, fmt};

pub use self::{
Expand All @@ -10,8 +11,10 @@ pub use self::{
balances_map::{BalancesMap, UnifiedMap},
big_num::BigNum,
campaign::{Campaign, CampaignId},
channel::{Channel, ChannelId, ChannelSpec, SpecValidator, SpecValidators},
channel::{ChannelId, ChannelSpec, SpecValidator, SpecValidators},
channel_v5::Channel,
config::Config,
deposit::Deposit,
event_submission::EventSubmission,
ipfs::IPFS,
unified_num::UnifiedNum,
Expand Down Expand Up @@ -43,6 +46,43 @@ pub mod targeting;
mod unified_num;
pub mod validator;

mod deposit {
use crate::{BigNum, UnifiedNum};
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct Deposit<N> {
pub total: N,
pub still_on_create2: N,
}

impl Deposit<UnifiedNum> {
pub fn to_precision(&self, precision: u8) -> Deposit<BigNum> {
Deposit {
total: self.total.to_precision(precision),
still_on_create2: self.total.to_precision(precision),
}
}

pub fn from_precision(
deposit: Deposit<BigNum>,
precision: u8,
) -> Option<Deposit<UnifiedNum>> {
let total = UnifiedNum::from_precision(deposit.total, precision);
let still_on_create2 = UnifiedNum::from_precision(deposit.still_on_create2, precision);

match (total, still_on_create2) {
(Some(total), Some(still_on_create2)) => Some(Deposit {
total,
still_on_create2,
}),
_ => None,
}
}
}
}

pub mod util {
pub use api::ApiUrl;

Expand Down
51 changes: 22 additions & 29 deletions primitives/src/sentry.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
use crate::{
balances::BalancesState,
channel::Channel as ChannelOld,
spender::Spender,
validator::{ApproveState, Heartbeat, MessageTypes, NewState, Type as MessageType},
Address, Balances, BigNum, Channel, ChannelId, ValidatorId, IPFS,
Address, Balances, BigNum, ChannelId, ValidatorId, IPFS,
};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -181,16 +182,6 @@ pub struct AggregateEvents {
pub event_payouts: HashMap<Address, BigNum>,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChannelListResponse {
pub channels: Vec<Channel>,
// TODO: Replace with `Pagination`
pub total_pages: u64,
pub total: u64,
pub page: u64,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Pagination {
Expand All @@ -210,6 +201,12 @@ pub struct LastApprovedResponse<S: BalancesState> {
pub heartbeats: Option<Vec<MessageResponse<Heartbeat>>>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LastApprovedQuery {
pub with_heartbeat: Option<String>,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct SuccessResponse {
pub success: bool,
Expand Down Expand Up @@ -244,7 +241,7 @@ pub struct ValidatorMessageResponse {

#[derive(Serialize, Deserialize, Debug)]
pub struct EventAggregateResponse {
pub channel: Channel,
pub channel: ChannelOld,
pub events: Vec<EventAggregate>,
}

Expand Down Expand Up @@ -304,32 +301,28 @@ impl fmt::Display for ChannelReport {
}

pub mod channel_list {
use crate::ValidatorId;
use chrono::{serde::ts_seconds, DateTime, Utc};
use crate::{channel_v5::Channel, ValidatorId};
use serde::{Deserialize, Serialize};

use super::Pagination;

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChannelListResponse {
pub channels: Vec<Channel>,
#[serde(flatten)]
pub pagination: Pagination,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ChannelListQuery {
#[serde(default = "default_page")]
#[serde(default)]
// default is `u64::default()` = `0`
pub page: u64,
/// filters the list on `valid_until >= valid_until_ge`
/// It should be the same timestamp format as the `Channel.valid_until`: **seconds**
#[serde(with = "ts_seconds", default = "Utc::now", rename = "validUntil")]
pub valid_until_ge: DateTime<Utc>,
pub creator: Option<String>,
/// filters the channels containing a specific validator if provided
pub validator: Option<ValidatorId>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LastApprovedQuery {
pub with_heartbeat: Option<String>,
}

fn default_page() -> u64 {
0
}
}

pub mod campaign {
Expand Down
26 changes: 5 additions & 21 deletions primitives/src/spender.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,6 @@
use crate::{channel_v5::Channel, Address, BalancesMap, UnifiedNum};
use chrono::{DateTime, Utc};
use crate::{channel_v5::Channel, Address, Deposit, UnifiedNum};
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct Deposit {
pub total: UnifiedNum,
pub still_on_create2: UnifiedNum,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct SpenderLeaf {
Expand All @@ -26,27 +18,19 @@ pub struct Spender {
pub struct Spendable {
pub spender: Address,
pub channel: Channel,
pub deposit: Deposit,
pub deposit: Deposit<UnifiedNum>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Aggregate {
pub spender: Address,
pub channel: Channel,
pub balances: BalancesMap,
pub created: DateTime<Utc>,
}
#[cfg(feature = "postgres")]
mod postgres {
use super::*;
use tokio_postgres::Row;

impl From<Row> for Spendable {
fn from(row: Row) -> Self {
impl From<&Row> for Spendable {
fn from(row: &Row) -> Self {
Self {
spender: row.get("spender"),
channel: row.get("channel"),
channel: Channel::from(row),
deposit: Deposit {
total: row.get("total"),
still_on_create2: row.get("still_on_create2"),
Expand Down
Loading