update init, add reset, fix create table

This commit is contained in:
boneyard93501 2021-03-08 17:35:11 -06:00
parent 0569b82717
commit e9777ba772
3 changed files with 141 additions and 66 deletions

View File

@ -13,15 +13,18 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
use crate::*;
use fluence::fce; use fluence::fce;
use fce_sqlite_connector; use fce_sqlite_connector;
use fce_sqlite_connector::{Connection, State, Value}; use fce_sqlite_connector::{Connection, State, Value};
use std::sync::atomic::{AtomicBool, Ordering};
fn create_table(conn: &Connection) -> std::result::Result<(), fce_sqlite_connector::Error> { use crate::{AUTH, PAYWALL};
use crate::get_connection;
use crate::auth::is_owner;
pub fn create_table(conn: &Connection) -> std::result::Result<(), fce_sqlite_connector::Error> {
let res = conn.execute( let res = conn.execute(
" "
create table if not exists reward_blocks ( create table if not exists reward_blocks (
@ -56,6 +59,11 @@ fn create_table(conn: &Connection) -> std::result::Result<(), fce_sqlite_connect
fn_name Text not null, fn_name Text not null,
json_path Text not null json_path Text not null
); );
create table if not exists api_keys (
provider text not null primary key,
api_key text not null
);
", ",
); );
res res
@ -63,14 +71,14 @@ fn create_table(conn: &Connection) -> std::result::Result<(), fce_sqlite_connect
#[fce] #[fce]
pub fn update_reward_blocks(data_string: String) -> bool { pub fn update_reward_blocks(data_string: String) -> bool {
if !is_owner() { if AUTH.load(Ordering::Relaxed) && !is_owner() {
return false; return false;
} }
let obj:serde_json::Value = serde_json::from_str(&data_string).unwrap(); let obj:serde_json::Value = serde_json::from_str(&data_string).unwrap();
let obj = obj["result"].clone(); let obj = obj["result"].clone();
let conn = fce_sqlite_connector::open(DB_PATH).unwrap(); let conn = get_connection();
let insert = "insert or ignore into reward_blocks values(?, ?, ?, ?)"; let insert = "insert or ignore into reward_blocks values(?, ?, ?, ?)";
let mut ins_cur = conn.prepare(insert).unwrap().cursor(); let mut ins_cur = conn.prepare(insert).unwrap().cursor();
@ -130,7 +138,7 @@ impl RewardBlock {
#[fce] #[fce]
pub fn get_latest_reward_block() -> RewardBlock { pub fn get_latest_reward_block() -> RewardBlock {
// let db_path = "/tmp/db.sqlite"; // let db_path = "/tmp/db.sqlite";
let conn = fce_sqlite_connector::open(DB_PATH).unwrap(); let conn = get_connection();
let mut reward_block = RewardBlock::from_err(); let mut reward_block = RewardBlock::from_err();
let select = conn.prepare("select * from reward_blocks order by block_number desc limit 1"); let select = conn.prepare("select * from reward_blocks order by block_number desc limit 1");
@ -148,11 +156,9 @@ pub fn get_latest_reward_block() -> RewardBlock {
result result
} }
#[fce] #[fce]
pub fn get_reward_block(block_number: u32) -> RewardBlock { pub fn get_reward_block(block_number: u32) -> RewardBlock {
let conn = fce_sqlite_connector::open(DB_PATH).unwrap(); let conn = get_connection();
let mut reward_block = RewardBlock::from_err(); let mut reward_block = RewardBlock::from_err();
let stmt = "select * from reward_blocks where block_number = ?"; let stmt = "select * from reward_blocks where block_number = ?";
@ -190,7 +196,7 @@ impl MinerRewards {
#[fce] #[fce]
pub fn get_miner_rewards(miner_address: String) -> MinerRewards { pub fn get_miner_rewards(miner_address: String) -> MinerRewards {
let conn = fce_sqlite_connector::open(DB_PATH).unwrap(); let conn = get_connection();
let stmt = "select block_reward from reward_blocks where block_miner = ?"; let stmt = "select block_reward from reward_blocks where block_miner = ?";
let select = conn.prepare(stmt); let select = conn.prepare(stmt);
@ -210,3 +216,17 @@ pub fn get_miner_rewards(miner_address: String) -> MinerRewards {
miner_rewards miner_rewards
} }
#[fce]
#[derive(Debug)]
pub struct UpdateResult {
pub success: bool,
pub err_str: String,
}
#[fce]
pub fn update_balance(user_id: String, tx_id: String, chain_id:u32) -> bool {
// check balance
true
}

View File

@ -26,14 +26,17 @@ use std::path::{Path, PathBuf};
use serde::Deserialize; use serde::Deserialize;
use serde_json; use serde_json;
use std::sync::atomic::{AtomicBool, Ordering};
use crate::crud::create_table;
use crate::auth::is_owner;
// const DB_PATH: &str = "/tmp/db_1.sqlite";
const DB_PATH: &str = "/tmp/fluence_service_db.sqlite"; const DB_PATH: &str = "/tmp/fluence_service_db.sqlite";
mod crud; mod crud;
mod auth; mod auth;
mod paywall; // mod paywall;
fn main() { fn main() {
@ -42,44 +45,100 @@ fn main() {
const KOVAN_ACCT: &str = ""; const KOVAN_ACCT: &str = "";
pub enum EthereumChains { pub static AUTH: AtomicBool = AtomicBool::new(false);
MAINNET = 1, pub static PAYWALL: AtomicBool = AtomicBool::new(false);
ROPSTEN = 3, pub static INIT: AtomicBool = AtomicBool::new(false);
RINKEBY = 4,
GOERLI = 5,
KOVAN = 42,
}
fn get_connection() -> Connection { fn get_connection() -> Connection {
Connection::open(DB_PATH).unwrap() Connection::open(DB_PATH).unwrap()
} }
#[fce] #[fce]
pub fn init_service() -> bool { #[derive(Debug)]
let conn = fce_sqlite_connector::open(DB_PATH).unwrap(); pub struct InitResult {
let res = create_table(&conn); pub success: bool,
match res { pub err_msg: String,
Ok(_) => true, }
Err(_) => false,
impl InitResult {
fn success() -> Self {
InitResult {success: true, err_msg: String::from(""),}
}
fn error(err_msg: String) -> Self {
InitResult {success: false, err_msg,}
} }
} }
#[fce]
pub fn init_service(is_auth:bool, is_paywall: bool, api_data: String) -> InitResult {
if INIT.load(Ordering::Relaxed) {
return InitResult::error("Service already initiated".into());
}
let conn = get_connection();
let res = create_table(&conn);
println!("create tables: {:?}", res);
if res.is_err() {
return InitResult::error("Failure to create tables".into());
}
AUTH.store(is_auth, Ordering::Relaxed);
PAYWALL.store(is_paywall, Ordering::Relaxed);
pub fn is_owner() -> bool { if api_data.len() > 0 {
let meta = fluence::get_call_parameters(); let tokens: Vec<&str> = api_data.as_str().split(":").collect();
let caller = meta.init_peer_id; if tokens.len() != 2{
let owner = meta.service_creator_peer_id; return InitResult::error("Invalid api data".into());
}
caller == owner let ins_stmt = "insert or ignore into api_keys values (?, ?)";
let mut ins_cur = conn.prepare(ins_stmt).unwrap().cursor();
let insert = ins_cur.bind(
&[Value::String(tokens[0].into()),
Value::String(tokens[1].into()),
]
);
if insert.is_err() {
return InitResult::error("Failure to insert api data".into());
}
} else {
return InitResult::error("Missing api data".into());
}
//Todo: implement rollbacks
INIT.store(true, Ordering::Relaxed);
InitResult::success()
} }
/* #[fce]
pub fn owner_nuclear_reset() -> bool {
if !is_owner() {
return false;
}
AUTH.store(false, Ordering::Relaxed);
PAYWALL.store(false, Ordering::Relaxed);
INIT.store(false, Ordering::Relaxed);
let conn = get_connection();
let t_names = vec!["api_keys", "reward_blocks", "payments", "costs", "security"];
for t_name in t_names {
let stmt = format!("delete from {}", t_name);
let mut del_cur = conn.prepare(&stmt).unwrap().cursor();
del_cur.next().unwrap();
}
true
}
/*
#[fce] #[fce]
fn get_balance(reference_id: String, ) { fn get_balance(reference_id: String, ) {
let conn = fce_sqlite_connector::open(DB_PATH).unwrap(); let conn = fce_sqlite_connector::open(DB_PATH).unwrap();
@ -89,35 +148,14 @@ fn get_balance(reference_id: String, ) {
let mut miner_rewards = MinerRewards::new(miner_address.clone()); let mut miner_rewards = MinerRewards::new(miner_address.clone());
} }
*/
fn update_payments() { /*
fn check_funding(compute_units: u32, unit_cost: u32) -> bool {
let conn = get_connection();
}
#[fce]
pub struct AccountStatus {
}
fn check_funding(compute_units: u32) -> bool {
let conn = fce_sqlite_connector::open(DB_PATH).unwrap();
let stmt = "select block_reward from reward_blocks where block_miner = ?";
let select = conn.prepare(stmt);
let mut miner_rewards = MinerRewards::new(miner_address.clone());
match select {
Ok(s) => {
let mut select = s.cursor();
select.bind(&[Value::String(miner_address)]).unwrap();
while let Some(row) = select.next().unwrap() {
println!("reward row {:?}", row);
miner_rewards.rewards.push(row[0].as_integer().unwrap().to_string());
};
}
Err(e) => log::error!("suck it"), //(format!("{:?}",
let req_balance:i64 = (compute_units * unit_cost).into();
get_balance(user_id)
true
} }
*/ */

View File

@ -15,18 +15,34 @@
*/ */
use uuid::Uuid; use uuid::Uuid;
use ed25519_dalek::{Signature, Verifier, PublicKey};
use crate::get_connection; use crate::get_connection;
pub fn sig_check(pub_key: &[u8], message: &[u8], signature: &[u8]) -> bool { pub enum EthereumChains {
pk = PublicKey::from_bytes(pub_key); MAINNET = 1,
ROPSTEN = 3,
pk.verify(message, signature) RINKEBY = 4,
GOERLI = 5,
KOVAN = 42,
} }
// pub fn query(user_id: String, signature: bytes) fn sig_check(pub_key: &[u8], message: &[u8], signature: [u8;64]) -> bool {
let pk = PublicKey::from_bytes(pub_key).unwrap();
let signature = Signature::new(signature);
match pk.verify(message, &signature) {
Ok(_) => true,
Err(_) => false
}
}
#[fce]
#[derive(Debug)]
pub struct DepositResult { pub struct DepositResult {
success: bool, success: bool,
balance: String, balance: String,
@ -54,10 +70,11 @@ impl DepositResult {
pub fn deposit(user_id:String, tx_id: String, chain_id: u32, pub_key: &[u8], signature: &[u8]) -> DepositResult { pub fn deposit(user_id:String, tx_id: String, chain_id: u32, pub_key: &[u8], signature: &[u8]) -> DepositResult {
let mut user_id:String = user_id; let mut user_id:String = user_id;
if user_id.len() == 0 { if user_id.len() == 0 {
user_id = uuid:Uuid(); let user_id = Uuid::new_v4();
} }
let stmt = "insert into table ??? where user_id = ? on conflict (user_id) do update set balance += ?"; let stmt = "insert into table ??? where user_id = ? on conflict (user_id) do update set balance += ?";
DepositResult::failure("no_good".into(), "0".into())
} }