Skip to content

Commit

Permalink
Merge pull request #14 from kanari-network/db-dev
Browse files Browse the repository at this point in the history
Db dev
  • Loading branch information
jamesatomc authored Feb 7, 2025
2 parents aed4ad7 + e8c5c1d commit 775c798
Show file tree
Hide file tree
Showing 5 changed files with 143 additions and 5 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ categories = ["development-tools"]
keywords = ["blockchain", "sdk"]
homepage = "https://kanari.network"
documentation = "https://docs.kanari.network"
version = "0.0.3"
version = "0.0.4"
authors = ["Kanari Network"]
license = "Apache-2.0"
repository = "https://github.com/kanari-network/kanari-sdk"
Expand Down
50 changes: 49 additions & 1 deletion crates/core/k2/src/blockchain/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ use bincode;
use consensus_pos::Blake3Algorithm;
use dirs;
use mona_storage::{BlockchainStorage, RocksDBStorage, StorageError};

use mona_storage::{FileStorage, StorageError2};
use std::path::Path;

use std::collections::{HashMap, VecDeque};
use std::fs;
Expand Down Expand Up @@ -65,6 +66,7 @@ pub enum BlockchainError {
Storage(StorageError),
Balance(String),
Initialization(String),
FileStorage(StorageError2),
}

impl From<StorageError> for BlockchainError {
Expand All @@ -73,12 +75,58 @@ impl From<StorageError> for BlockchainError {
}
}

impl From<StorageError2> for BlockchainError {
fn from(error: StorageError2) -> Self {
BlockchainError::FileStorage(error)
}
}


// Add file storage function
pub fn store_file(file_path: &Path) -> Result<String, BlockchainError> {
let filename = file_path.file_name()
.and_then(|name| name.to_str())
.unwrap_or("")
.to_string();

let storage = FileStorage::upload(file_path, filename)?;
let file_id = storage.id.to_string();

// Create file storage transaction
let transaction = Transaction {
sender: "system".to_string(),
receiver: file_id.clone(),
amount: 0,
timestamp: std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs(),
gas_cost: TRANSACTION_GAS_COST,
signature: None,
tx_type: TransactionType::FileStore,
data: storage.path.to_str().unwrap_or("").as_bytes().to_vec(),
coin_type: None
};

// Add transaction to current block
unsafe {
if let Some(last_block) = BLOCKCHAIN.back_mut() {
last_block.transactions.push(transaction);
save_blockchain()?;
}
}

Ok(file_id)
}


impl std::fmt::Display for BlockchainError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
BlockchainError::Storage(e) => write!(f, "Storage error: {}", e),
BlockchainError::Balance(e) => write!(f, "Balance error: {}", e),
BlockchainError::Initialization(e) => write!(f, "Initialization error: {}", e),
BlockchainError::FileStorage(storage_error2) => write!(f, "File storage error: {}", storage_error2),
}
}
}
Expand Down
1 change: 1 addition & 0 deletions crates/core/k2/src/transaction/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use sha2::{Sha256, Digest};
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub enum TransactionType {
Transfer,
FileStore,
MoveModuleDeploy(Vec<u8>),
MoveExecute {
module_name: String,
Expand Down
5 changes: 4 additions & 1 deletion crates/rpc/rpc-api/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,7 @@ serde.workspace = true

network.workspace = true
consensus-pos.workspace = true
k2.workspace = true
k2.workspace = true

mona-storage = { path = "../../../monaos/mona-storage" }
base64 = "0.22.1"
90 changes: 88 additions & 2 deletions crates/rpc/rpc-api/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,86 @@
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use futures::FutureExt;
use jsonrpc_core::{IoHandler, Params, Result as JsonRpcResult};
use jsonrpc_core::{IoHandler, Params, Result as JsonRpcResult, Error as RpcError};
use jsonrpc_http_server::{ServerBuilder, AccessControlAllowOrigin, DomainsValidation};
use k2::{blockchain::BLOCKCHAIN, chain_id::CHAIN_ID};
use network::NetworkConfig;
use serde_json::Value as JsonValue;
use serde_json::{json, Value as JsonValue};
use mona_storage::file_storage::{FileStorage, StorageError2};
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
use serde::{Deserialize, Serialize};



#[derive(Serialize)]
struct FileInfo {
id: String,
filename: String,
size: u64,
content_type: String,
}

#[derive(Deserialize)]
struct UploadParams {
filename: String,
data: String, // base64 encoded file content
}

// Add new RPC methods for file operations
fn upload_file(params: Params) -> JsonRpcResult<JsonValue> {
let upload_params: UploadParams = params.parse()
.map_err(|e| RpcError::invalid_params(format!("Invalid parameters: {}", e)))?;

// Decode base64 data
let file_data = BASE64.decode(upload_params.data)
.map_err(|e| RpcError::invalid_params(format!("Invalid base64 data: {}", e)))?;

// Initialize storage
FileStorage::init_storage()
.map_err(|e| RpcError::internal_error())?;

// Create new storage instance
let storage = FileStorage::new()
.map_err(|e| RpcError::internal_error())?;

// Store the file
match storage.store(&upload_params.filename, &file_data) {
Ok(stored) => {
let file_info = FileInfo {
id: stored.id.to_string(),
filename: stored.metadata.filename,
size: stored.metadata.size,
content_type: stored.metadata.content_type,
};
Ok(serde_json::to_value(file_info).unwrap())
},
Err(e) => Err(RpcError::internal_error())
}
}

fn get_file(params: Params) -> JsonRpcResult<JsonValue> {
let file_id: String = params.parse()
.map_err(|e| RpcError::invalid_params(format!("Invalid file ID: {}", e)))?;

match FileStorage::get_by_id(&file_id) {
Ok(storage) => {
let file_data = std::fs::read(&storage.path)
.map_err(|_| RpcError::internal_error())?;

let response = json!({
"id": storage.id.to_string(),
"filename": storage.metadata.filename,
"size": storage.metadata.size,
"content_type": storage.metadata.content_type,
"data": BASE64.encode(file_data)
});

Ok(response)
},
Err(StorageError2::NotFound) => Err(RpcError::invalid_params("File not found")),
Err(_) => Err(RpcError::internal_error())
}
}


// RPC server
fn get_latest_block(_params: Params) -> JsonRpcResult<JsonValue> {
Expand Down Expand Up @@ -36,6 +112,16 @@ fn get_block_by_index(params: Params) -> JsonRpcResult<JsonValue> {
pub async fn start_rpc_server(network_config: NetworkConfig) {
let mut io = IoHandler::new();

// Add file operations
io.add_method("upload_file", |params| {
futures::future::ready(upload_file(params)).boxed()
});

io.add_method("get_file", |params| {
futures::future::ready(get_file(params)).boxed()
});


// Add RPC methods
io.add_method("get_latest_block", |params| {
futures::future::ready(get_latest_block(params)).boxed()
Expand Down

0 comments on commit 775c798

Please sign in to comment.