Skip to content

Commit

Permalink
Attempt to inset data into metadata
Browse files Browse the repository at this point in the history
  • Loading branch information
macpie committed Jun 4, 2024
1 parent 504a16d commit 220bfeb
Show file tree
Hide file tree
Showing 8 changed files with 182 additions and 30 deletions.
3 changes: 3 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
CREATE TABLE IF NOT EXISTS public.key_to_assets (
address character varying(255) NOT NULL,
dao character varying(255) NULL,
asset character varying(255) NULL,
entity_key bytea NULL,
bump_seed integer NULL,
refreshed_at timestamp with time zone NULL,
created_at timestamp with time zone NOT NULL,
key_serialization jsonb NULL
);

ALTER TABLE
public.key_to_assets
ADD
CONSTRAINT key_to_assets_pkey PRIMARY KEY (address)
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
CREATE TABLE IF NOT EXISTS public.mobile_hotspot_infos (
address character varying(255) NOT NULL,
asset character varying(255) NULL,
bump_seed integer NULL,
location numeric NULL,
is_full_hotspot boolean NULL,
num_location_asserts integer NULL,
refreshed_at timestamp with time zone NULL,
created_at timestamp with time zone NOT NULL,
is_active boolean NULL,
dc_onboarding_fee_paid numeric NULL,
device_type jsonb NOT NULL
);

ALTER TABLE
public.mobile_hotspot_infos
ADD
CONSTRAINT mobile_hotspot_infos_pkey PRIMARY KEY (address)
3 changes: 3 additions & 0 deletions test_mobile/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ chrono = { workspace = true }
helium-crypto = { workspace = true }
prost = { workspace = true }
rand = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
sqlx = { workspace = true }
tonic = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
Expand Down
2 changes: 1 addition & 1 deletion test_mobile/tests/common/docker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ impl Docker {
impl Drop for Docker {
fn drop(&mut self) {
// This code runs when the scope exits, including if the test fails.
tracing::info!("Test finished. Performing cleanup.");
tracing::debug!("Docker dropped");
match self.stop() {
Ok(_) => tracing::info!("docker stack stopped"),
Err(e) => tracing::error!("docker compose stopped failed: {:?}", e),
Expand Down
161 changes: 138 additions & 23 deletions test_mobile/tests/common/hotspot.rs
Original file line number Diff line number Diff line change
@@ -1,28 +1,50 @@
use anyhow::Result;
use backon::{ExponentialBuilder, Retryable};
use helium_crypto::{KeyTag, Keypair, Sign};
use helium_proto::services::poc_mobile::{
Client as PocMobileClient, CoverageObjectReqV1, RadioHexSignalLevel, SpeedtestReqV1,
WifiHeartbeatReqV1,
use chrono::Utc;
use h3o::CellIndex;
use helium_crypto::{KeyTag, Keypair, PublicKey, PublicKeyBinary, Sign};
use helium_proto::services::{
mobile_config::DeviceType,
poc_mobile::{
Client as PocMobileClient, CoverageObjectReqV1, RadioHexSignalLevel, SpeedtestReqV1,
WifiHeartbeatReqV1,
},
};
use prost::Message;
use rand::rngs::OsRng;
use sqlx::postgres::PgPoolOptions;
use std::str::FromStr;
use test_mobile::cli::assignment::CENTER_CELL;
use tonic::{metadata::MetadataValue, transport::Channel, Request};
use uuid::Uuid;

use crate::common::{hours_ago, keypair_to_bs58, now, TimestampToDateTime};
use crate::common::{hours_ago, now, TimestampToDateTime};

pub struct Hotspot {
client: PocMobileClient<Channel>,
mobile_client: PocMobileClient<Channel>,
api_token: String,
keypair: Keypair,
wallet: Keypair,
serial: String,
location: CellIndex,
}

#[test]
fn it_works() {
let keypair = Keypair::generate(KeyTag::default(), &mut OsRng);
let x: Vec<u8> = keypair.public_key().into();
println!("{:?}", keypair);
println!("{:?}", x);
println!("{:?}", keypair.public_key().to_vec());
println!("{:?}", bs58::encode(x.clone()).into_string());
println!(
"{:?}",
PublicKey::from_bytes(x.clone()).unwrap().to_string()
);
println!("{:?}", PublicKeyBinary::from(x).to_string());
}

impl Hotspot {
pub async fn new(api_token: String) -> Self {
pub async fn new(api_token: String, index: u64) -> Result<Self> {
let endpoint = "http://127.0.0.1:9080";

let client = (|| PocMobileClient::connect(endpoint))
Expand All @@ -31,17 +53,26 @@ impl Hotspot {
.expect("client connect");

let keypair = Keypair::generate(KeyTag::default(), &mut OsRng);
let wallet = Keypair::generate(KeyTag::default(), &mut OsRng);

let b58 = keypair_to_bs58(&keypair);
let b58 = keypair.public_key().to_string();

tracing::info!("hotspot {b58} connected to ingester");

Self {
client,
let location = h3o::CellIndex::try_from(index).unwrap();

let result = populate_mobile_metadata(&keypair, &wallet, location).await?;

tracing::info!("{:?}", result);

Ok(Self {
mobile_client: client,
api_token: format!("Bearer {api_token}"),
keypair,
wallet,
serial: b58,
}
location,
})
}

pub async fn submit_speedtest(
Expand All @@ -53,7 +84,7 @@ impl Hotspot {
let timestamp = now();

let mut speedtest_req = SpeedtestReqV1 {
pub_key: self.keypair.public_key().into(),
pub_key: self.keypair.public_key().to_vec(),
serial: self.serial.clone(),
timestamp,
upload_speed,
Expand All @@ -74,7 +105,7 @@ impl Hotspot {
speedtest_req
);

let res = self.client.submit_speedtest(request).await?;
let res = self.mobile_client.submit_speedtest(request).await?;
tracing::debug!(
"submitted speedtest @ {} = {:?}",
timestamp.to_datetime(),
Expand All @@ -85,16 +116,14 @@ impl Hotspot {
}

pub async fn submit_coverage_object(&mut self, uuid: Uuid) -> Result<()> {
let location = h3o::CellIndex::try_from(CENTER_CELL).unwrap();

let coverage_claim_time = now() - hours_ago(24);

let mut coverage_object_req = CoverageObjectReqV1 {
pub_key: self.keypair.public_key().into(),
pub_key: self.keypair.public_key().to_vec(),
uuid: uuid.as_bytes().to_vec(),
coverage_claim_time,
coverage: vec![RadioHexSignalLevel {
location: location.to_string(),
location: self.location.to_string(),
signal_level: 3,
signal_power: 1000,
}],
Expand All @@ -116,7 +145,7 @@ impl Hotspot {
coverage_object_req
);

let res = self.client.submit_coverage_object(request).await?;
let res = self.mobile_client.submit_coverage_object(request).await?;
tracing::debug!(
"submitted coverage_object @ {} = {:?}",
coverage_claim_time.to_datetime(),
Expand All @@ -129,11 +158,20 @@ impl Hotspot {
pub async fn submit_wifi_heartbeat(&mut self, when: u64, coverage_object: Uuid) -> Result<()> {
let timestamp = now() - when;

let center_loc = self
.location
.center_child(h3o::Resolution::Thirteen)
.expect("center child");

let lat_lon = h3o::LatLng::from(center_loc);

let mut wifi_heartbeat_req = WifiHeartbeatReqV1 {
pub_key: self.keypair.public_key().into(),
pub_key: self.keypair.public_key().to_vec(),
timestamp,
lat: 19.642310,
lon: -155.990626,
// lat: 19.642310,
// lon: -155.990626,
lat: lat_lon.lat(),
lon: lat_lon.lng(),
location_validation_timestamp: timestamp,
operation_mode: true,
coverage_object: coverage_object.as_bytes().to_vec(),
Expand All @@ -152,7 +190,7 @@ impl Hotspot {
wifi_heartbeat_req
);

let res = self.client.submit_wifi_heartbeat(request).await?;
let res = self.mobile_client.submit_wifi_heartbeat(request).await?;
tracing::debug!(
"submitted wifi_heartbeat @ {} = {:?}",
timestamp.to_datetime(),
Expand All @@ -174,3 +212,80 @@ impl Hotspot {
request
}
}

impl Drop for Hotspot {
fn drop(&mut self) {
tracing::debug!("Hotspot dropped")
}
}

async fn populate_mobile_metadata(
keypair: &Keypair,
wallet: &Keypair,
location: CellIndex,
) -> Result<()> {
let database_url = "postgres://postgres:postgres@localhost:5432/mobile_metadata";

let pool = PgPoolOptions::new()
.max_connections(5)
.connect(database_url)
.await?;

let uuid = Uuid::new_v4();
let h3_index: u64 = location.into();
let device_type = DeviceType::WifiIndoor;
let device_type_json = serde_json::to_value(&device_type)?;

let wallet_b58 = wallet.public_key().to_string();

sqlx::query(
r#"
INSERT INTO mobile_hotspot_infos (
address, asset, bump_seed,
location, is_full_hotspot, num_location_asserts,
refreshed_at, created_at, is_active,
dc_onboarding_fee_paid, device_type
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
"#,
)
.bind(wallet_b58.as_str()) // address
.bind(uuid.to_string()) // asset
.bind(254) // bump_seed
.bind(h3_index as i64) // location
.bind(true) // is_full_hotspot
.bind(1) // num_location_asserts
.bind(Utc::now()) // refreshed_at
.bind(Utc::now()) // created_at
.bind(true) // is_active
.bind(400000) // dc_onboarding_fee_paid
.bind(device_type_json) // device_type
.execute(&pool)
.await?;

// let pk_binary: PublicKeyBinary = keypair.public_key().to_owned().into();
let pk_binary = PublicKeyBinary::from_str(keypair.public_key().to_string().as_str())?;
let entity_key = bs58::decode(pk_binary.to_string()).into_vec()?;

sqlx::query(
r#"
INSERT INTO key_to_assets (
address, asset, bump_seed,
created_at, dao, entity_key,
refreshed_at
)
VALUES ($1, $2, $3, $4, $5, $6, $7)
"#,
)
.bind(wallet_b58.as_str()) // address
.bind(uuid.to_string()) // asset
.bind(254) // bump_seed
.bind(Utc::now()) // created_at
.bind("BQ3MCuTT5zVBhNfQ4SjMh3NPVhFy73MPV8rjfq5d1zie") // dao
.bind(entity_key) // entity_key
.bind(Utc::now()) // refreshed_at
.execute(&pool)
.await?;

Ok(())
}
5 changes: 0 additions & 5 deletions test_mobile/tests/common/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use std::time::{SystemTime, UNIX_EPOCH};

use chrono::{DateTime, NaiveDateTime, TimeZone, Utc};
use helium_crypto::Keypair;

pub mod docker;
pub mod hotspot;
Expand All @@ -26,10 +25,6 @@ pub fn now() -> u64 {
.as_millis() as u64
}

pub fn keypair_to_bs58(keypair: &Keypair) -> String {
bs58::encode(keypair.public_key().to_vec()).into_string()
}

pub fn hours_ago(hours: i64) -> u64 {
chrono::Duration::hours(hours).num_milliseconds() as u64
}
5 changes: 4 additions & 1 deletion test_mobile/tests/integration_test.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use anyhow::Result;
use common::{docker::Docker, hotspot::Hotspot, hours_ago};
use test_mobile::cli::assignment::CENTER_CELL;
use uuid::Uuid;

mod common;
Expand All @@ -23,7 +24,9 @@ async fn main() -> Result<()> {
}
}

let mut hotspot1 = Hotspot::new("api-token".to_string()).await;
let api_token = "api-token".to_string();

let mut hotspot1 = Hotspot::new(api_token, CENTER_CELL).await?;
let co_uuid = Uuid::new_v4();

hotspot1.submit_coverage_object(co_uuid).await?;
Expand Down

0 comments on commit 220bfeb

Please sign in to comment.