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
* limitations under the License.
*/
use crate::*;
use fluence::fce;
use fce_sqlite_connector;
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(
"
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,
json_path Text not null
);
create table if not exists api_keys (
provider text not null primary key,
api_key text not null
);
",
);
res
@ -63,14 +71,14 @@ fn create_table(conn: &Connection) -> std::result::Result<(), fce_sqlite_connect
#[fce]
pub fn update_reward_blocks(data_string: String) -> bool {
if !is_owner() {
if AUTH.load(Ordering::Relaxed) && !is_owner() {
return false;
}
let obj:serde_json::Value = serde_json::from_str(&data_string).unwrap();
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 mut ins_cur = conn.prepare(insert).unwrap().cursor();
@ -130,7 +138,7 @@ impl RewardBlock {
#[fce]
pub fn get_latest_reward_block() -> RewardBlock {
// 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 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
}
#[fce]
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 stmt = "select * from reward_blocks where block_number = ?";
@ -190,7 +196,7 @@ impl MinerRewards {
#[fce]
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 select = conn.prepare(stmt);
@ -210,3 +216,17 @@ pub fn get_miner_rewards(miner_address: String) -> MinerRewards {
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_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";
mod crud;
mod auth;
mod paywall;
// mod paywall;
fn main() {
@ -42,44 +45,100 @@ fn main() {
const KOVAN_ACCT: &str = "";
pub enum EthereumChains {
MAINNET = 1,
ROPSTEN = 3,
RINKEBY = 4,
GOERLI = 5,
KOVAN = 42,
pub static AUTH: AtomicBool = AtomicBool::new(false);
pub static PAYWALL: AtomicBool = AtomicBool::new(false);
pub static INIT: AtomicBool = AtomicBool::new(false);
}
fn get_connection() -> Connection {
Connection::open(DB_PATH).unwrap()
}
#[fce]
pub fn init_service() -> bool {
let conn = fce_sqlite_connector::open(DB_PATH).unwrap();
let res = create_table(&conn);
match res {
Ok(_) => true,
Err(_) => false,
#[derive(Debug)]
pub struct InitResult {
pub success: bool,
pub err_msg: String,
}
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 {
let meta = fluence::get_call_parameters();
let caller = meta.init_peer_id;
let owner = meta.service_creator_peer_id;
if api_data.len() > 0 {
let tokens: Vec<&str> = api_data.as_str().split(":").collect();
if tokens.len() != 2{
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]
fn get_balance(reference_id: String, ) {
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());
}
*/
fn update_payments() {
}
#[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!("{:?}",
/*
fn check_funding(compute_units: u32, unit_cost: u32) -> bool {
let conn = get_connection();
let req_balance:i64 = (compute_units * unit_cost).into();
get_balance(user_id)
true
}
*/

View File

@ -15,18 +15,34 @@
*/
use uuid::Uuid;
use ed25519_dalek::{Signature, Verifier, PublicKey};
use crate::get_connection;
pub fn sig_check(pub_key: &[u8], message: &[u8], signature: &[u8]) -> bool {
pk = PublicKey::from_bytes(pub_key);
pk.verify(message, signature)
pub enum EthereumChains {
MAINNET = 1,
ROPSTEN = 3,
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 {
success: bool,
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 {
let mut user_id:String = user_id;
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 += ?";
DepositResult::failure("no_good".into(), "0".into())
}