Import sp_client through sdk_common

This commit is contained in:
Sosthene 2024-05-28 11:31:18 +02:00
parent de133cc0a3
commit 7da19aa28c
5 changed files with 91 additions and 76 deletions

View File

@ -8,8 +8,6 @@ name = "sdk_client"
crate-type = ["cdylib"]
[dependencies]
sp_client= { path = "../../../sp-client" }
# sp_client= { git = "https://github.com/Sosthene00/sp-client", branch = "sp_client" }
anyhow = "1.0"
serde = { version = "1.0.188", features = ["derive"] }
serde_json = "1.0"

View File

@ -14,39 +14,41 @@ use anyhow::Error as AnyhowError;
use sdk_common::crypto::{
AeadCore, Aes256Decryption, Aes256Encryption, Aes256Gcm, AnkSharedSecret, KeyInit, Purpose,
};
use sdk_common::sp_client::bitcoin::blockdata::fee_rate;
use sdk_common::sp_client::bitcoin::consensus::{deserialize, serialize};
use sdk_common::sp_client::bitcoin::hashes::HashEngine;
use sdk_common::sp_client::bitcoin::hashes::{sha256, Hash};
use sdk_common::sp_client::bitcoin::hex::{
parse, DisplayHex, FromHex, HexToArrayError, HexToBytesError,
};
use sdk_common::sp_client::bitcoin::key::Secp256k1;
use sdk_common::sp_client::bitcoin::secp256k1::ecdh::shared_secret_point;
use sdk_common::sp_client::bitcoin::secp256k1::{PublicKey, SecretKey};
use sdk_common::sp_client::bitcoin::{Amount, Network, OutPoint, Psbt, Transaction, Txid};
use sdk_common::sp_client::silentpayments::utils as sp_utils;
use sdk_common::sp_client::silentpayments::{Error as SpError, Network as SpNetwork};
use serde_json::{Error as SerdeJsonError, Value};
use shamir::SecretData;
use sp_client::bitcoin::blockdata::fee_rate;
use sp_client::bitcoin::consensus::{deserialize, serialize};
use sp_client::bitcoin::hashes::HashEngine;
use sp_client::bitcoin::hashes::{sha256, Hash};
use sp_client::bitcoin::hex::{parse, DisplayHex, FromHex, HexToArrayError, HexToBytesError};
use sp_client::bitcoin::key::Secp256k1;
use sp_client::bitcoin::secp256k1::ecdh::shared_secret_point;
use sp_client::bitcoin::secp256k1::{PublicKey, SecretKey};
use sp_client::bitcoin::{Amount, Network, OutPoint, Psbt, Transaction, Txid};
use sp_client::silentpayments::utils as sp_utils;
use sp_client::silentpayments::{Error as SpError, Network as SpNetwork};
use sdk_common::sp_client::silentpayments::sending::SilentPaymentAddress;
use serde::{Deserialize, Serialize};
use sp_client::silentpayments::sending::SilentPaymentAddress;
use tsify::Tsify;
use wasm_bindgen::convert::FromWasmAbi;
use wasm_bindgen::prelude::*;
use sdk_common::network::{
self, AnkFlag, AnkNetworkMsg, CachedMessage, CachedMessageStatus, FaucetMessage, NewTxMessage,
CipherMessage,
self, AnkFlag, AnkNetworkMsg, CachedMessage, CachedMessageStatus, CipherMessage, FaucetMessage,
NewTxMessage,
};
use sdk_common::silentpayments::{
create_transaction, create_transaction_for_address_with_shared_secret,
create_transaction_spend_outpoint, map_outputs_to_sp_address,
};
use sp_client::spclient::{
use sdk_common::sp_client::spclient::{
derive_keys_from_seed, OutputList, OutputSpendStatus, OwnedOutput, Recipient, SpClient,
};
use sp_client::spclient::{SpWallet, SpendKey};
use sdk_common::sp_client::spclient::{SpWallet, SpendKey};
use crate::user::{lock_connected_user, User, UserWallets, CONNECTED_USER};
use crate::{images, lock_messages, CACHEDMESSAGES};
@ -102,32 +104,32 @@ impl From<HexToArrayError> for ApiError {
}
}
impl From<sp_client::bitcoin::psbt::PsbtParseError> for ApiError {
fn from(value: sp_client::bitcoin::psbt::PsbtParseError) -> Self {
impl From<sdk_common::sp_client::bitcoin::psbt::PsbtParseError> for ApiError {
fn from(value: sdk_common::sp_client::bitcoin::psbt::PsbtParseError) -> Self {
ApiError {
message: value.to_string(),
}
}
}
impl From<sp_client::bitcoin::psbt::ExtractTxError> for ApiError {
fn from(value: sp_client::bitcoin::psbt::ExtractTxError) -> Self {
impl From<sdk_common::sp_client::bitcoin::psbt::ExtractTxError> for ApiError {
fn from(value: sdk_common::sp_client::bitcoin::psbt::ExtractTxError) -> Self {
ApiError {
message: value.to_string(),
}
}
}
impl From<sp_client::bitcoin::secp256k1::Error> for ApiError {
fn from(value: sp_client::bitcoin::secp256k1::Error) -> Self {
impl From<sdk_common::sp_client::bitcoin::secp256k1::Error> for ApiError {
fn from(value: sdk_common::sp_client::bitcoin::secp256k1::Error) -> Self {
ApiError {
message: value.to_string(),
}
}
}
impl From<sp_client::bitcoin::consensus::encode::Error> for ApiError {
fn from(value: sp_client::bitcoin::consensus::encode::Error) -> Self {
impl From<sdk_common::sp_client::bitcoin::consensus::encode::Error> for ApiError {
fn from(value: sdk_common::sp_client::bitcoin::consensus::encode::Error) -> Self {
ApiError {
message: value.to_string(),
}
@ -423,13 +425,10 @@ fn handle_recover_transaction(
// we inspect inputs looking for links with previous tx
for input in tx.input.iter() {
if let Some(pos) = messages
.iter()
.position(|m| {
if let Some(pos) = messages.iter().position(|m| {
debug!("{:?}", Some(input.previous_output));
m.confirmed_by == Some(input.previous_output)
})
{
}) {
let message = messages.get_mut(pos).unwrap();
// If we are receiver, that's pretty much it, just set status to complete
message.status = CachedMessageStatus::Complete;
@ -511,31 +510,40 @@ fn handle_recover_transaction(
// eiter this is notification, a challenge, or response to a challenge
// if notification, commitment is the same than in the message
// if challenge or response, commitment is H(commitment | b_scan), b_scan being different depending on who we are
if let Some(message) = messages
.iter()
.find(|m| {
if commitment.is_empty() || m.commitment.is_none() { return false }
if let Some(message) = messages.iter().find(|m| {
if commitment.is_empty() || m.commitment.is_none() {
return false;
}
match m.status {
CachedMessageStatus::SentWaitingConfirmation => {
// commitment we're looking for is simply what's in the message
m.commitment.as_ref().map(|c| Vec::from_hex(&c).unwrap()).unwrap() == commitment
},
CachedMessageStatus::MustSpendConfirmation | CachedMessageStatus::ReceivedMustConfirm => {
m.commitment
.as_ref()
.map(|c| Vec::from_hex(&c).unwrap())
.unwrap()
== commitment
}
CachedMessageStatus::MustSpendConfirmation
| CachedMessageStatus::ReceivedMustConfirm => {
// we compute the potential commitment
let m_commitment = m.commitment.as_ref().map(|c| Vec::from_hex(&c).unwrap()).unwrap();
let mut buf = [0u8;64];
let m_commitment = m
.commitment
.as_ref()
.map(|c| Vec::from_hex(&c).unwrap())
.unwrap();
let mut buf = [0u8; 64];
buf[..32].copy_from_slice(&m_commitment);
buf[32..].copy_from_slice(&sp_wallet.get_client().get_scan_key().secret_bytes());
buf[32..]
.copy_from_slice(&sp_wallet.get_client().get_scan_key().secret_bytes());
let mut engine = sha256::HashEngine::default();
engine.write_all(&buf).unwrap();
let hash = sha256::Hash::from_engine(engine);
hash.to_byte_array().to_vec() == commitment
},
_ => return false
}
})
{
_ => return false,
}
}) {
return Ok(message.clone());
} else {
return Err(anyhow::Error::msg(
@ -624,7 +632,7 @@ pub fn parse_network_msg(raw: String, fee_rate: u32) -> ApiResult<CachedMessage>
debug!("Faucet msg returned with an error: {}", error);
}
unimplemented!();
},
}
AnkFlag::Cipher => {
// let's try to decrypt with keys we found in transactions but haven't used yet
let mut messages = lock_messages()?;
@ -738,7 +746,9 @@ pub fn answer_confirmation_transaction(
message = m;
} else {
return Err(ApiError { message: format!("Can't find message for id {}", message_id) });
return Err(ApiError {
message: format!("Can't find message for id {}", message_id),
});
}
let sp_address: SilentPaymentAddress =
@ -798,7 +808,9 @@ pub fn create_confirmation_transaction(
message = m;
} else {
return Err(ApiError { message: format!("Can't find message for id {}", message_id) });
return Err(ApiError {
message: format!("Can't find message for id {}", message_id),
});
}
let sp_address: SilentPaymentAddress = message.sender.as_ref().unwrap().as_str().try_into()?;
@ -836,7 +848,10 @@ pub fn create_confirmation_transaction(
let final_tx = signed_psbt.extract_tx()?;
message.confirmed_by = Some(OutPoint { txid: final_tx.txid(), vout: recipients_vouts[0] as u32 });
message.confirmed_by = Some(OutPoint {
txid: final_tx.txid(),
vout: recipients_vouts[0] as u32,
});
Ok(createTransactionReturn {
txid: final_tx.txid().to_string(),
@ -891,7 +906,10 @@ pub fn create_notification_transaction(
shared_secret.to_byte_array().to_lower_hex_string()
);
let cipher = encrypt_with_key(serde_json::to_string(&message)?, shared_secret.to_byte_array().to_lower_hex_string())?;
let cipher = encrypt_with_key(
serde_json::to_string(&message)?,
shared_secret.to_byte_array().to_lower_hex_string(),
)?;
// update our cache
let sp_address2vouts = map_outputs_to_sp_address(&signed_psbt)?;
@ -913,7 +931,6 @@ pub fn create_notification_transaction(
new_msg.recipient = Some(address);
new_msg.sender = Some(sp_wallet.get_client().get_receiving_address());
new_msg.status = CachedMessageStatus::SentWaitingConfirmation;
// plaintext and ciphertext to be added later when sending the encrypted message
lock_messages()?.push(new_msg.clone());
Ok(createTransactionReturn {

View File

@ -1,7 +1,7 @@
use anyhow::{Error, Result};
use img_parts::{jpeg::Jpeg, Bytes, ImageEXIF};
use sdk_common::sp_client::bitcoin::secp256k1::SecretKey;
use serde::{Deserialize, Serialize};
use sp_client::bitcoin::secp256k1::SecretKey;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BackUpImage(Vec<u8>);

View File

@ -1,8 +1,8 @@
use std::fmt::DebugStruct;
use sdk_common::sp_client::silentpayments::sending::SilentPaymentAddress;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use sp_client::silentpayments::sending::SilentPaymentAddress;
use tsify::Tsify;
use wasm_bindgen::prelude::*;

View File

@ -1,13 +1,13 @@
use anyhow::{Error, Result};
use rand::{self, thread_rng, Rng, RngCore};
use sdk_common::sp_client::bitcoin::hashes::Hash;
use sdk_common::sp_client::bitcoin::hashes::HashEngine;
use sdk_common::sp_client::bitcoin::hex::{DisplayHex, FromHex};
use sdk_common::sp_client::bitcoin::secp256k1::SecretKey;
use sdk_common::sp_client::bitcoin::secp256k1::ThirtyTwoByteHash;
use sdk_common::sp_client::spclient::SpClient;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use sp_client::bitcoin::hashes::Hash;
use sp_client::bitcoin::hashes::HashEngine;
use sp_client::bitcoin::hex::{DisplayHex, FromHex};
use sp_client::bitcoin::secp256k1::SecretKey;
use sp_client::bitcoin::secp256k1::ThirtyTwoByteHash;
use sp_client::spclient::SpClient;
use tsify::Tsify;
use wasm_bindgen::prelude::*;
@ -18,11 +18,11 @@ use std::io::{Cursor, Read, Write};
use std::str::FromStr;
use std::sync::{Mutex, MutexGuard, OnceLock};
use sp_client::bitcoin::secp256k1::constants::SECRET_KEY_SIZE;
use sp_client::silentpayments::bitcoin_hashes::sha256;
use sp_client::silentpayments::sending::SilentPaymentAddress;
use sp_client::spclient::SpendKey;
use sp_client::spclient::{OutputList, SpWallet};
use sdk_common::sp_client::bitcoin::secp256k1::constants::SECRET_KEY_SIZE;
use sdk_common::sp_client::silentpayments::bitcoin_hashes::sha256;
use sdk_common::sp_client::silentpayments::sending::SilentPaymentAddress;
use sdk_common::sp_client::spclient::SpendKey;
use sdk_common::sp_client::spclient::{OutputList, SpWallet};
use crate::peers::Peer;
use crate::user;