Skip to content

Commit

Permalink
updates
Browse files Browse the repository at this point in the history
  • Loading branch information
Valentine-Mario committed Sep 22, 2023
1 parent 187d721 commit 83f9140
Show file tree
Hide file tree
Showing 5 changed files with 257 additions and 40 deletions.
3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ blake2 = "0.10.4"
sha3 = "0.10.6"
bs58 = "0.4.0"
hex = "0.4.3"
secp256k1 = {version = "0.21.3", features = [ "rand-std", "recovery"]}
secp256k1 = {version = "0.21.3", features = [ "rand-std", "recovery", "global-context"]}
base16 = "0.2.1"
bitcoin_hashes = "0.11.0"
reqwest = { version ="0.11.13", features = ["blocking", "json"] }
Expand All @@ -32,6 +32,7 @@ listenfd = "0.3"
actix-cors="0.5.1"
handlebars = "4.3.7"
tonic-build = "0.7.2"
bincode = "1.3.3"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[build-dependencies]
Expand Down
1 change: 1 addition & 0 deletions rhoast_client/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ hex = { workspace = true }
reqwest = { workspace = true }
chrono = { workspace = true }
tokio = {workspace = true}
bincode = {workspace = true}


[build-dependencies]
Expand Down
74 changes: 47 additions & 27 deletions rhoast_client/src/util/deploy_util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use bitcoin_hashes::{sha256, Hash};
use rhoast_utils::error::Error;
use rhoast_utils::pub_from_private::{get_pub_key, get_seckey_from_string};
use rhoast_utils::{get_blake2_hash::get_blake2_hash, SIG_ALGORITHM};
use secp256k1::{ecdsa, Message, PublicKey, Secp256k1, SecretKey, Signing, Verification};
use secp256k1::{ecdsa, Message, PublicKey, KeyPair, Secp256k1, SecretKey, Signing, Verification};

pub fn get_first_block(block_info: &Vec<DataWithBlockInfo>) -> &DataWithBlockInfo {
&block_info[0]
Expand All @@ -24,37 +24,37 @@ pub fn get_value_from_block(block_info: &Vec<DataWithBlockInfo>) -> Option<&Par>
}

//pass in secret key as a byte slice
pub fn sign_secp_256k1<C: Signing + Verification>(
secp: &Secp256k1<C>,
msg: &[u8],
seckey: &[u8],
) -> Result<ecdsa::SerializedSignature, Error> {
let msg = sha256::Hash::hash(msg);
match Message::from_slice(&msg) {
Ok(msg) => match SecretKey::from_slice(&seckey) {
Ok(seckey) => {
let sig = secp.sign_ecdsa(&msg, &seckey);
let pubkey = PublicKey::from_secret_key(secp, &seckey);
match secp.verify_ecdsa(&msg, &sig, &pubkey) {
Ok(_) => Ok(sig.serialize_der()),
Err(_) => Err(Error::DeployUtil("Failed to verify signature")),
}
}
Err(_) => Err(Error::DeployUtil("error writing secret to slice")),
},
Err(_) => Err(Error::DeployUtil("error writing message to slice")),
}
}
// pub fn sign_secp_256k1<C: Signing + Verification>(
// secp: &Secp256k1<C>,
// msg: &[u8],
// seckey: &SecretKey,
// ) -> Result<Vec<u8>, Error> {
// let msg = sha256::Hash::hash(msg);
// match Message::from_slice(&msg) {
// Ok(msg) => match SecretKey::from_slice(&seckey) {
// Ok(seckey) => {
// let sig = secp.sign_ecdsa(&msg, &seckey);
// let pubkey = PublicKey::from_secret_key(secp, &seckey);
// match secp.verify_ecdsa(&msg, &sig, &pubkey) {
// Ok(_) => {
// Ok(sig.serialize_der()[..].to_vec())
// },
// Err(_) => Err(Error::DeployUtil("Failed to verify signature")),
// }
// }
// Err(_) => Err(Error::DeployUtil("error writing secret to slice")),
// },
// Err(_) => Err(Error::DeployUtil("error writing message to slice")),
// }
// }

unsafe fn any_as_u8_slice<T: Sized>(p: &T) -> &[u8] {
::std::slice::from_raw_parts((p as *const T) as *const u8, ::std::mem::size_of::<T>())
}

pub fn get_deploy_data(payload: &DeployDataPayload) -> Result<DeployDataRequest, Error> {
//sign sec key
let sec_key_hash = get_seckey_from_string(&payload.private_key)?;
//get public key
let pub_key = get_pub_key(&sec_key_hash);


let deploy_data = DeployData {
timestamp: payload.timestamp,
Expand All @@ -64,14 +64,34 @@ pub fn get_deploy_data(payload: &DeployDataPayload) -> Result<DeployDataRequest,
phlo_limit: payload.phlo_limit,
valid_after_block_number: payload.valid_after_block_number,
};
let to_sign = unsafe { any_as_u8_slice(&deploy_data) };
let to_sign = bincode::serialize(&deploy_data).unwrap();

let hash = get_blake2_hash(&to_sign, Some(32))?;
let secp = Secp256k1::new();
let signature = sign_secp_256k1(&secp, &hash, &sec_key_hash[..])?.to_string();
let sig= secp.sign_ecdsa(&Message::from_slice(&hash).unwrap(), &sec_key_hash);
let pubkey = PublicKey::from_secret_key(&secp, &sec_key_hash);
let verify=secp.verify_ecdsa(&Message::from_slice(&hash).unwrap(), &sig, &pubkey).unwrap();
let signature = buf_2_hex(&sig.serialize_der().to_vec());

println!("{:?} {:?}", verify, signature);



Ok(DeployDataRequest {
data: deploy_data,
deployer: pub_key.to_string(),
signature: signature,
sig_algorithm: SIG_ALGORITHM.to_string(),
})
}


fn text_2_buf(value: &str)->Vec<u8>{
value.as_bytes().to_vec()
}
fn buf_2_hex(value: &Vec<u8>)->String{
hex::encode(value)
}
// fn sign_byte(value: &Vec<u8>, mut output: Vec<u8>, sk: Vec<u8>){
// sign(&mut output, &value, &sk.as_slice());
// }
3 changes: 3 additions & 0 deletions rhoast_functions/src/.vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"nuxt.isNuxtApp": false
}
216 changes: 204 additions & 12 deletions rhoast_wallet/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,208 @@
use rhoast_wallet::error::Error;
use serde_json::{json, Value};
use std::collections::BTreeMap;

pub mod rho;
#[tokio::main]
async fn main() {
let node = rhoast_wallet::Node::new(
&"https://observer.services.mainnet.rchain.coop".to_string(),
&"".to_string(),
&"".to_string(),
&"".to_string(),
&"".to_string(),
);
let balance = node
.check_balance(&"1111Zfr2UB1YXuD6zccsPhqthiik4jfQV8W8aoncbvVGtfU8QJQei".to_string())
.await
.unwrap();
println!("{}", balance)
// let node = rhoast_wallet::Node::new(
// &"https://observer.services.mainnet.rchain.coop".to_string(),
// &"".to_string(),
// &"".to_string(),
// &"".to_string(),
// &"".to_string(),
// );
// let balance = node
// .check_balance(&"1111Zfr2UB1YXuD6zccsPhqthiik4jfQV8W8aoncbvVGtfU8QJQei".to_string())
// .await
// .unwrap();
// println!("{}", balance)
let k="{\"expr\":{\"ExprList\":{\"data\": [{\"expr\":{\"ExprInt\":{\"data\": 30}}}, {\"expr\":{\"ExprString\":{\"data\": \"hello\"}}}]}}}";
let j="{\"expr\":{\"ExprMap\":{\"data\": {\"item\" : {\"expr\":{\"ExprString\":{\"data\": \"hello\"}}}, \"vile\": {\"expr\":{\"ExprString\":{\"data\": \"hello\"}}}} }}}";
let l="{\"expr\":{\"ExprUnforg\":{\"data\":{\"UnforgPrivate\":{\"data\": \"hello\"}}}}}";
println!("{:?}", map_rnode_respose(j));
}

#[derive(Debug)]
struct Unforgable {
pub unforg_private: Value,
pub unforg_deploy: Value,
pub unforg_deployer: Value,
}

#[derive(Debug)]
enum MapResult {
OneValue(Value),
VecValue(Vec<MapResult>),
MapValue(BTreeMap<String, MapResult>),
Unforge(Unforgable),
}
fn map_rnode_respose(response: &str) -> Result<MapResult, Error> {
let value: std::result::Result<serde_json::Value, serde_json::Error> =
serde_json::from_str(&response);
let mut map: BTreeMap<String, MapResult> = BTreeMap::new();
let mut unforge_struct = Unforgable {
unforg_deploy: Value::Null,
unforg_private: Value::Null,
unforg_deployer: Value::Null,
};

match value {
Ok(json) => {
use MapResult::*;

if json.get("expr").is_some() {
let expr = json.get("expr").unwrap();
//check for expr string
if expr.get("ExprString").is_some()
&& expr.get("ExprString").unwrap().get("data").is_some()
{
Ok(OneValue(
expr.get("ExprString")
.unwrap()
.get("data")
.unwrap()
.to_owned(),
))
}
// check for expr uri
else if expr.get("ExprUri").is_some()
&& expr.get("ExprUri").unwrap().get("data").is_some()
{
Ok(OneValue(
expr.get("ExprUri").unwrap().get("data").unwrap().to_owned(),
))
}
//check for expr int
else if expr.get("ExprInt").is_some()
&& expr.get("ExprInt").unwrap().get("data").is_some()
{
Ok(OneValue(
expr.get("ExprInt").unwrap().get("data").unwrap().to_owned(),
))
}
//check for expr boolean
else if expr.get("ExprBool").is_some()
&& expr.get("ExprBool").unwrap().get("data").is_some()
{
Ok(OneValue(
expr.get("ExprBool")
.unwrap()
.get("data")
.unwrap()
.to_owned(),
))
}
//check for list
else if expr.get("ExprList").is_some()
&& expr.get("ExprList").unwrap().get("data").is_some()
{
let list = expr
.get("ExprList")
.unwrap()
.get("data")
.unwrap()
.as_array()
.to_owned()
.unwrap();
let list_map = list
.into_iter()
.map(|item| map_rnode_respose(&item.to_string()).unwrap())
.collect::<Vec<MapResult>>();

Ok(VecValue(list_map))
}
//check for tuple
else if expr.get("ExprTuple").is_some()
&& expr.get("ExprTuple").unwrap().get("data").is_some()
{
let list = expr
.get("ExprTuple")
.unwrap()
.get("data")
.unwrap()
.as_array()
.to_owned()
.unwrap();
let list_map = list
.into_iter()
.map(|item| map_rnode_respose(&item.to_string()).unwrap())
.collect::<Vec<MapResult>>();

Ok(VecValue(list_map))
}
//check for set
else if expr.get("ExprSet").is_some()
&& expr.get("ExprSet").unwrap().get("data").is_some()
{
let list = expr
.get("ExprSet")
.unwrap()
.get("data")
.unwrap()
.as_array()
.to_owned()
.unwrap();
let list_map = list
.into_iter()
.map(|item| map_rnode_respose(&item.to_string()).unwrap())
.collect::<Vec<MapResult>>();

Ok(VecValue(list_map))
}
//check for map
else if expr.get("ExprMap").is_some()
&& expr.get("ExprMap").unwrap().get("data").is_some()
{
let object = expr
.get("ExprMap")
.unwrap()
.get("data")
.unwrap()
.as_object()
.to_owned()
.unwrap();

for key in object.keys().into_iter() {
map.insert(
String::from(key),
map_rnode_respose(&object.get(key).unwrap().to_string()).unwrap(),
);
}
Ok(MapValue(map))
}
//check for unforgable
else if expr.get("ExprUnforg").is_some()
&& expr.get("ExprUnforg").unwrap().get("data").is_some()
{
let object = expr
.get("ExprUnforg")
.unwrap()
.get("data")
.unwrap()
.as_object()
.to_owned()
.unwrap();
for key in object.keys().into_iter() {
if key == "UnforgPrivate" {
unforge_struct.unforg_private =
expr["ExprUnforg"]["data"][key]["data"].to_owned();
} else if key == "UnforgDeploy" {
unforge_struct.unforg_deploy =
expr["ExprUnforg"]["data"][key]["data"].to_owned();
} else if key == "UnforgDeployer" {
unforge_struct.unforg_deployer =
expr["ExprUnforg"]["data"][key]["data"].to_owned();
}
}
Ok(Unforge(unforge_struct))
} else {
Err(Error::CheckBlance(""))
}
} else {
Err(Error::CheckBlance("Error getting expr"))
}
}
Err(_) => Err(Error::CheckBlance("Error parsing json")),
}
}

0 comments on commit 83f9140

Please sign in to comment.