Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[DAT-101] Clean up premint topics and declare them via config #6

Merged
merged 3 commits into from
Mar 26, 2024
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
49 changes: 49 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::types::PremintName;
use envconfig::Envconfig;

#[derive(Envconfig, Debug)]
Expand All @@ -22,6 +23,10 @@ pub struct Config {

#[envconfig(from = "PEER_LIMIT", default = "1000")]
pub peer_limit: u64,

// Comma separated list of default premint types to process
#[envconfig(from = "PREMINT_TYPES", default = "zora_premint_v2")]
pub premint_types: String,
}

impl Config {
Expand All @@ -32,8 +37,52 @@ impl Config {
"127.0.0.1".to_string()
}
}

pub fn premint_names(&self) -> Vec<PremintName> {
self.premint_types
.split(',')
.map(|s| PremintName(s.to_string()))
.collect()
}
}

pub fn init() -> Config {
Config::init_from_env().expect("Failed to load config")
}

#[cfg(test)]
mod test {
#[test]
fn test_premint_names() {
let config = super::Config {
seed: 0,
port: 7777,
connect_external: false,
db_url: None,
persist_state: false,
prune_minted_premints: false,
peer_limit: 1000,
premint_types: "simple,zora_premint_v2".to_string(),
};

let names = config.premint_names();
assert_eq!(names.len(), 2);
assert_eq!(names[0].0, "simple");
assert_eq!(names[1].0, "zora_premint_v2");

let config = super::Config {
seed: 0,
port: 7777,
connect_external: false,
db_url: None,
persist_state: false,
prune_minted_premints: false,
peer_limit: 1000,
premint_types: "zora_premint_v2".to_string(),
};

let names = config.premint_names();
assert_eq!(names.len(), 1);
assert_eq!(names[0].0, "zora_premint_v2");
}
}
31 changes: 20 additions & 11 deletions src/p2p.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::config::Config;
use crate::controller::{P2PEvent, SwarmCommand};
use crate::types::{MintpoolNodeInfo, Premint, PremintTypes};
use crate::types::{MintpoolNodeInfo, Premint, PremintName, PremintTypes};
use alloy_primitives::private::derive_more::Display;
use eyre::WrapErr;
use libp2p::core::ConnectedPoint;
use libp2p::futures::StreamExt;
Expand All @@ -26,6 +27,7 @@ pub struct SwarmController {
event_sender: tokio::sync::mpsc::Sender<P2PEvent>,
max_peers: u64,
local_mode: bool,
premint_names: Vec<PremintName>,
}

impl SwarmController {
Expand All @@ -42,7 +44,8 @@ impl SwarmController {
command_receiver,
event_sender,
max_peers: config.peer_limit,
local_mode: config.connect_external == false,
local_mode: !config.connect_external,
premint_names: config.premint_names(),
}
}

Expand Down Expand Up @@ -90,17 +93,19 @@ impl SwarmController {
}

pub async fn run(&mut self, port: u64, listen_ip: String) -> eyre::Result<()> {
let registry_topic = gossipsub::IdentTopic::new("announce::premints");
self.swarm
.listen_on(format!("/ip4/{listen_ip}/tcp/{port}").parse()?)?;

let topic = gossipsub::IdentTopic::new("zora-1155-v1-mints");
self.swarm.behaviour_mut().gossipsub.subscribe(&topic)?;
let registry_topic = announce_topic();
self.swarm
.behaviour_mut()
.gossipsub
.subscribe(&registry_topic)?;

self.swarm
.listen_on(format!("/ip4/{listen_ip}/tcp/{port}").parse()?)?;
for premint_name in self.premint_names.iter() {
let topic = premint_name.msg_topic();
self.swarm.behaviour_mut().gossipsub.subscribe(&topic)?;
}

self.run_loop().await;
Ok(())
Expand Down Expand Up @@ -235,7 +240,7 @@ impl SwarmController {
}

fn broadcast_message(&mut self, message: PremintTypes) -> eyre::Result<()> {
let topic = gossipsub::IdentTopic::new("zora-1155-v1-mints");
let topic = message.metadata().kind.msg_topic();
let msg = message.to_json().wrap_err("failed to serialize message")?;

self.swarm
Expand All @@ -257,7 +262,7 @@ impl SwarmController {
} else {
peer_id.to_string()
};
let registry_topic = gossipsub::IdentTopic::new("announce::premints");
let registry_topic = announce_topic();

if let Err(err) = self
.swarm
Expand All @@ -270,8 +275,8 @@ impl SwarmController {
}

async fn handle_gossipsub_event(&mut self, event: gossipsub::Event) -> eyre::Result<()> {
tracing::info!("Gossipsub event: {:?}", event);
let registry_topic = gossipsub::IdentTopic::new("announce::premints");
tracing::debug!("Gossipsub event: {:?}", event);
let registry_topic = announce_topic();
match event {
gossipsub::Event::Message { message, .. } => {
let msg = String::from_utf8_lossy(&message.data);
Expand Down Expand Up @@ -406,3 +411,7 @@ pub struct NetworkState {
pub gossipsub_peers: Vec<PeerId>,
pub all_external_addresses: Vec<Multiaddr>,
}

fn announce_topic() -> gossipsub::IdentTopic {
gossipsub::IdentTopic::new("mintpool::announce")
}
4 changes: 3 additions & 1 deletion src/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ impl PremintStorage {
VALUES (?, ?, ?, ?, ?, ?, ?)
"#,
metadata.id,
metadata.kind,
metadata.kind.0,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If I'm understanding this syntax correctly it would pull the first field from the PremintName struct/tuple. If other fields were added before it, that would break this one, right? Not sure what the convention is here, but in python we could use a NamedTuple here to make the intention clear.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PremintName is a wrapper on the type String, in this case kind.0 just pulls the inner value of string since the outer type PremintName doesn't implement sqlx's traits required for storage via macro

signer,
metadata.chain_id,
collection_address,
Expand Down Expand Up @@ -121,6 +121,7 @@ mod test {
persist_state: false,
prune_minted_premints: false,
peer_limit: 1000,
premint_types: "simple".to_string(),
};

let store = PremintStorage::new(&config).await;
Expand All @@ -141,6 +142,7 @@ mod test {
persist_state: false,
prune_minted_premints: false,
peer_limit: 1000,
premint_types: "simple".to_string(),
};

let store = PremintStorage::new(&config).await;
Expand Down
32 changes: 26 additions & 6 deletions src/types.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,20 @@
use alloy_primitives::private::derive_more::Display;
use alloy_primitives::{Address, U256};
use libp2p::{Multiaddr, PeerId};
use libp2p::{gossipsub, Multiaddr, PeerId};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use sqlx::{Decode, Encode};
use std::fmt::Debug;

#[derive(Debug, Display)]
pub struct PremintName(pub String);

impl PremintName {
pub fn msg_topic(&self) -> gossipsub::IdentTopic {
gossipsub::IdentTopic::new(format!("mintpool::{:?}", self))
}
}

#[derive(Debug)]
pub struct MintpoolNodeInfo {
pub peer_id: PeerId,
Expand All @@ -13,7 +24,7 @@ pub struct MintpoolNodeInfo {
#[derive(Debug)]
pub struct PremintMetadata {
pub id: String,
pub kind: String,
pub kind: PremintName,
pub signer: Address,
pub chain_id: i64,
pub collection_address: Address,
Expand All @@ -23,6 +34,7 @@ pub struct PremintMetadata {

pub trait Premint: Serialize + DeserializeOwned + Debug + Clone {
fn metadata(&self) -> PremintMetadata;
fn kind_id() -> PremintName;
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
Expand All @@ -44,8 +56,8 @@ impl PremintTypes {
}
}

impl Premint for PremintTypes {
fn metadata(&self) -> PremintMetadata {
impl PremintTypes {
pub fn metadata(&self) -> PremintMetadata {
match self {
PremintTypes::Simple(p) => p.metadata(),
PremintTypes::V2(p) => p.metadata(),
Expand All @@ -65,14 +77,18 @@ impl Premint for SimplePremint {
fn metadata(&self) -> PremintMetadata {
PremintMetadata {
id: format!("{:?}:{:?}:{:?}", self.chain_id, self.sender, self.token_id),
kind: "simple".to_string(),
kind: Self::kind_id(),
signer: self.sender,
chain_id: self.chain_id as i64,
collection_address: Address::default(),
token_id: U256::from(self.token_id),
uri: self.media.clone(),
}
}

fn kind_id() -> PremintName {
PremintName("simple".to_string())
}
}

#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq)]
Expand All @@ -88,14 +104,18 @@ impl Premint for PremintV2Message {
fn metadata(&self) -> PremintMetadata {
PremintMetadata {
id: self.premint.uid.to_string(),
kind: "zora_premint_v2".to_string(),
kind: Self::kind_id(),
signer: self.collection.contract_admin,
chain_id: self.chain_id as i64,
collection_address: Address::default(), // TODO: source this
token_id: U256::from(self.premint.uid),
uri: self.premint.token_creation_config.token_uri.clone(),
}
}

fn kind_id() -> PremintName {
PremintName("zora_premint_v2".to_string())
}
}

#[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq)]
Expand Down
1 change: 1 addition & 0 deletions tests/p2p_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ mod build {
persist_state: false,
prune_minted_premints: false,
peer_limit,
premint_types: "simple,zora_premint_v2".to_string(),
};

let ctl = mintpool::run::start_swarm_and_controller(&config)
Expand Down
Loading