mirror of
https://github.com/darkrenaissance/darkfi.git
synced 2026-04-28 03:00:18 -04:00
Refactor for util feature.
This commit is contained in:
219
Cargo.toml
219
Cargo.toml
@@ -11,115 +11,140 @@ edition = "2021"
|
||||
[lib]
|
||||
name = "darkfi"
|
||||
|
||||
[dependencies.halo2_gadgets]
|
||||
git = "https://github.com/parazyd/halo2_gadgets.git"
|
||||
rev = "b45c527276bb2309f3b256eb5f45ccdcc5bd8c0f"
|
||||
features = ["dev-graph", "test-dependencies"]
|
||||
|
||||
# blockchain dependencies
|
||||
[dependencies.rocksdb]
|
||||
# TODO: Revert to upstream after bd966750ec861d687913d59a9939a1408ac53131 is merged.
|
||||
git = "https://github.com/parazyd/rust-rocksdb"
|
||||
rev = "bd966750ec861d687913d59a9939a1408ac53131"
|
||||
default-features = false
|
||||
features = ["zstd"]
|
||||
optional = true
|
||||
|
||||
[dependencies]
|
||||
# Crypto
|
||||
halo2 = {version = "=0.1.0-beta.1", features = ["dev-graph", "gadget-traces", "sanity-checks"]}
|
||||
incrementalmerkletree = "0.2.0"
|
||||
pasta_curves = "0.2.1"
|
||||
rand = "0.8.4"
|
||||
num-bigint = {version = "0.4.3", features = ["rand", "serde"]}
|
||||
blake2b_simd = "1.0.0"
|
||||
group = "0.11.0"
|
||||
crypto_api_chachapoly = "0.5.0"
|
||||
arrayvec = "0.7.2"
|
||||
sha2 = "0.9.8"
|
||||
|
||||
# Encoding and parsing
|
||||
bincode = "1.3.3"
|
||||
bs58 = "0.4.0"
|
||||
bytes = "1.1.0"
|
||||
hex = "0.4.3"
|
||||
toml = "0.5.8"
|
||||
url = "2.2.2"
|
||||
serde_json = "1.0.72"
|
||||
serde = {version = "1.0.130", features = ["derive"]}
|
||||
|
||||
# Async
|
||||
async-std = "1.10.0"
|
||||
async-trait = "0.1.51"
|
||||
async-channel = "1.6.1"
|
||||
native-tls = "0.2.8"
|
||||
async-native-tls = "0.4.0"
|
||||
async-executor = "1.4.1"
|
||||
futures = "0.3.17"
|
||||
smol = "1.2.5"
|
||||
|
||||
# Utilities
|
||||
anyhow = "1.0.49"
|
||||
clap = { version = "3.0.0", features = ["derive"] }
|
||||
dirs = "4.0.0"
|
||||
failure = "0.1.8"
|
||||
lazy_static = "1.4.0"
|
||||
log = "0.4.14"
|
||||
num_cpus = "1.13.0"
|
||||
signal-hook = "0.3.10"
|
||||
simplelog = "0.11.1"
|
||||
subtle = "2.4.1"
|
||||
thiserror = "1.0.30"
|
||||
|
||||
# Used for Websockets client implementation.
|
||||
async-tungstenite = "0.16.0"
|
||||
tungstenite = "0.16.0"
|
||||
# Async
|
||||
async-trait = {version = "0.1.52", optional = true}
|
||||
futures = {version = "0.3.19", optional = true}
|
||||
smol = {version = "1.2.5", optional = true}
|
||||
|
||||
#tui dependencies
|
||||
crossbeam-channel = { version = "0.5.1", optional = true}
|
||||
libc = { version = "0.2.112", optional = true}
|
||||
termion = { version = "1.5.6", optional = true}
|
||||
# Encoding
|
||||
hex = {version = "0.4.3", optional = true}
|
||||
serde = {version = "1.0.133", features = ["derive"], optional = true}
|
||||
serde_json = {version = "1.0.74", optional = true}
|
||||
|
||||
# node dependencies
|
||||
## Used for wallet management.
|
||||
sqlx = {version = "0.5.10", features = ["runtime-async-std-native-tls", "sqlite"], optional = true}
|
||||
libsqlite3-sys = {version = "0.23.1", features = ["bundled-sqlcipher"], optional = true }
|
||||
## Used for gatewayd network transport.
|
||||
zeromq = {version = "0.3.1", default-features = false, features = ["async-std-runtime", "all-transport"], optional = true }
|
||||
signal-hook-async-std = {version = "0.2.1", optional = true}
|
||||
# Utilities
|
||||
dirs = {version = "4.0.0", optional = true}
|
||||
|
||||
[workspace]
|
||||
members = ["bin/drk", "bin/darkfid", "bin/gateway"]
|
||||
exclude = ["bin/cashier", "bin/ircd", "bin/map"]
|
||||
# Misc
|
||||
num-bigint = {version = "0.4.3", optional = true}
|
||||
|
||||
[features]
|
||||
chain = ["rocksdb"]
|
||||
node = ["sqlx", "libsqlite3-sys", "zeromq", "signal-hook-async-std"]
|
||||
tui = ["termion", "libc", "crossbeam-channel"]
|
||||
async-runtime = ["async-trait", "futures", "smol"]
|
||||
util = ["async-runtime", "hex", "serde", "serde_json", "dirs",
|
||||
"num-bigint"]
|
||||
|
||||
[[example]]
|
||||
name = "net"
|
||||
path = "example/net.rs"
|
||||
required-features = ["node", "chain"]
|
||||
# [dependencies.halo2_gadgets]
|
||||
# git = "https://github.com/parazyd/halo2_gadgets.git"
|
||||
# rev = "b45c527276bb2309f3b256eb5f45ccdcc5bd8c0f"
|
||||
# features = ["dev-graph", "test-dependencies"]
|
||||
|
||||
[[example]]
|
||||
name = "tui"
|
||||
path = "example/tui_ex.rs"
|
||||
required-features = ["tui"]
|
||||
# # blockchain dependencies
|
||||
# [dependencies.rocksdb]
|
||||
# # TODO: Revert to upstream after bd966750ec861d687913d59a9939a1408ac53131 is merged.
|
||||
# git = "https://github.com/parazyd/rust-rocksdb"
|
||||
# rev = "bd966750ec861d687913d59a9939a1408ac53131"
|
||||
# default-features = false
|
||||
# features = ["zstd"]
|
||||
# optional = true
|
||||
|
||||
[[example]]
|
||||
name = "vm"
|
||||
path = "example/vm.rs"
|
||||
# [dependencies]
|
||||
# # Crypto
|
||||
# halo2 = {version = "=0.1.0-beta.1", features = ["dev-graph", "gadget-traces", "sanity-checks"]}
|
||||
# incrementalmerkletree = "0.2.0"
|
||||
# pasta_curves = "0.2.1"
|
||||
# rand = "0.8.4"
|
||||
# num-bigint = {version = "0.4.3", features = ["rand", "serde"]}
|
||||
# blake2b_simd = "1.0.0"
|
||||
# group = "0.11.0"
|
||||
# crypto_api_chachapoly = "0.5.0"
|
||||
# arrayvec = "0.7.2"
|
||||
# sha2 = "0.9.8"
|
||||
|
||||
[[example]]
|
||||
name = "vm_burn"
|
||||
path = "example/vm_burn.rs"
|
||||
# # Encoding and parsing
|
||||
# bincode = "1.3.3"
|
||||
# bs58 = "0.4.0"
|
||||
# bytes = "1.1.0"
|
||||
# hex = "0.4.3"
|
||||
# toml = "0.5.8"
|
||||
# url = "2.2.2"
|
||||
# serde_json = "1.0.72"
|
||||
# serde = {version = "1.0.130", features = ["derive"]}
|
||||
|
||||
[[example]]
|
||||
name = "tx"
|
||||
path = "example/tx.rs"
|
||||
required-features = ["node"]
|
||||
# # Async
|
||||
# async-std = "1.10.0"
|
||||
# async-trait = "0.1.51"
|
||||
# async-channel = "1.6.1"
|
||||
# native-tls = "0.2.8"
|
||||
# async-native-tls = "0.4.0"
|
||||
# async-executor = "1.4.1"
|
||||
# futures = "0.3.17"
|
||||
# smol = "1.2.5"
|
||||
|
||||
[[example]]
|
||||
name = "tree"
|
||||
path = "example/tree.rs"
|
||||
# # Utilities
|
||||
# anyhow = "1.0.49"
|
||||
# clap = { version = "3.0.0", features = ["derive"] }
|
||||
# dirs = "4.0.0"
|
||||
# failure = "0.1.8"
|
||||
# lazy_static = "1.4.0"
|
||||
# log = "0.4.14"
|
||||
# num_cpus = "1.13.0"
|
||||
# signal-hook = "0.3.10"
|
||||
# simplelog = "0.11.1"
|
||||
# subtle = "2.4.1"
|
||||
# thiserror = "1.0.30"
|
||||
|
||||
# # Used for Websockets client implementation.
|
||||
# async-tungstenite = "0.16.0"
|
||||
# tungstenite = "0.16.0"
|
||||
|
||||
# #tui dependencies
|
||||
# crossbeam-channel = { version = "0.5.1", optional = true}
|
||||
# libc = { version = "0.2.112", optional = true}
|
||||
# termion = { version = "1.5.6", optional = true}
|
||||
|
||||
# # node dependencies
|
||||
# ## Used for wallet management.
|
||||
# sqlx = {version = "0.5.10", features = ["runtime-async-std-native-tls", "sqlite"], optional = true}
|
||||
# libsqlite3-sys = {version = "0.23.1", features = ["bundled-sqlcipher"], optional = true }
|
||||
# ## Used for gatewayd network transport.
|
||||
# zeromq = {version = "0.3.1", default-features = false, features = ["async-std-runtime", "all-transport"], optional = true }
|
||||
# signal-hook-async-std = {version = "0.2.1", optional = true}
|
||||
|
||||
# [workspace]
|
||||
# members = ["bin/drk", "bin/darkfid", "bin/gateway"]
|
||||
# exclude = ["bin/cashier", "bin/ircd", "bin/map"]
|
||||
|
||||
# [features]
|
||||
# chain = ["rocksdb"]
|
||||
# node = ["sqlx", "libsqlite3-sys", "zeromq", "signal-hook-async-std"]
|
||||
# tui = ["termion", "libc", "crossbeam-channel"]
|
||||
|
||||
# [[example]]
|
||||
# name = "net"
|
||||
# path = "example/net.rs"
|
||||
# required-features = ["node", "chain"]
|
||||
|
||||
# [[example]]
|
||||
# name = "tui"
|
||||
# path = "example/tui_ex.rs"
|
||||
# required-features = ["tui"]
|
||||
|
||||
# [[example]]
|
||||
# name = "vm"
|
||||
# path = "example/vm.rs"
|
||||
|
||||
# [[example]]
|
||||
# name = "vm_burn"
|
||||
# path = "example/vm_burn.rs"
|
||||
|
||||
# [[example]]
|
||||
# name = "tx"
|
||||
# path = "example/tx.rs"
|
||||
# required-features = ["node"]
|
||||
|
||||
# [[example]]
|
||||
# name = "tree"
|
||||
# path = "example/tree.rs"
|
||||
|
||||
63
src/crypto/token_id.rs
Normal file
63
src/crypto/token_id.rs
Normal file
@@ -0,0 +1,63 @@
|
||||
/// Hash the external token ID and NetworkName param.
|
||||
/// If it fails, change the last 4 bytes and hash it again.
|
||||
/// Keep repeating until it works.
|
||||
pub fn generate_id(tkn_str: &str, network: &NetworkName) -> Result<DrkTokenId> {
|
||||
let mut id_string = network.to_string();
|
||||
id_string.push_str(tkn_str);
|
||||
|
||||
let mut data: Vec<u8> = serialize(&id_string);
|
||||
|
||||
let token_id = match deserialize::<DrkTokenId>(&data) {
|
||||
Ok(v) => v,
|
||||
Err(_) => {
|
||||
let mut counter = 0;
|
||||
loop {
|
||||
data.truncate(28);
|
||||
let serialized_counter = serialize(&counter);
|
||||
data.extend(serialized_counter.iter());
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(&data);
|
||||
let hash = hasher.finalize();
|
||||
let token_id = deserialize::<DrkTokenId>(&hash);
|
||||
if token_id.is_err() {
|
||||
counter += 1;
|
||||
continue
|
||||
}
|
||||
|
||||
return Ok(token_id.unwrap())
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Ok(token_id)
|
||||
}
|
||||
|
||||
/// YOLO
|
||||
pub fn generate_id2(tkn_str: &str, network: &NetworkName) -> Result<DrkTokenId> {
|
||||
let mut num = 0_u64;
|
||||
|
||||
match network {
|
||||
NetworkName::Solana => {
|
||||
for i in ['s', 'o', 'l'] {
|
||||
num += i as u64;
|
||||
}
|
||||
}
|
||||
NetworkName::Bitcoin => {
|
||||
for i in ['b', 't', 'c'] {
|
||||
num += i as u64;
|
||||
}
|
||||
}
|
||||
NetworkName::Ethereum => {
|
||||
for i in ['e', 't', 'h'] {
|
||||
num += i as u64;
|
||||
}
|
||||
}
|
||||
NetworkName::Empty => unimplemented!(),
|
||||
}
|
||||
|
||||
for i in tkn_str.chars() {
|
||||
num += i as u64;
|
||||
}
|
||||
|
||||
Ok(DrkTokenId::from(num))
|
||||
}
|
||||
@@ -8,6 +8,8 @@ use crate::{
|
||||
Error, Result,
|
||||
};
|
||||
|
||||
pub const ETH_NATIVE_TOKEN_ID: &str = "0x0000000000000000000000000000000000000000";
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct TokenList {
|
||||
tokens: Vec<Value>,
|
||||
@@ -119,6 +121,65 @@ impl DrkTokenList {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn assign_id(
|
||||
network: &NetworkName,
|
||||
token: &str,
|
||||
sol_tokenlist: &TokenList,
|
||||
eth_tokenlist: &TokenList,
|
||||
btc_tokenlist: &TokenList,
|
||||
) -> Result<String> {
|
||||
match network {
|
||||
NetworkName::Solana => {
|
||||
// (== 44) can represent a Solana base58 token mint address
|
||||
if token.len() == 44 {
|
||||
Ok(token.to_string())
|
||||
} else {
|
||||
let tok_lower = token.to_lowercase();
|
||||
symbol_to_id(&tok_lower, sol_tokenlist)
|
||||
}
|
||||
}
|
||||
NetworkName::Bitcoin => {
|
||||
if token.len() == 34 {
|
||||
Ok(token.to_string())
|
||||
} else {
|
||||
let tok_lower = token.to_lowercase();
|
||||
symbol_to_id(&tok_lower, btc_tokenlist)
|
||||
}
|
||||
}
|
||||
NetworkName::Ethereum => {
|
||||
// (== 42) can represent a erc20 token mint address
|
||||
if token.len() == 42 {
|
||||
Ok(token.to_string())
|
||||
} else if token == "eth" {
|
||||
Ok(ETH_NATIVE_TOKEN_ID.to_string())
|
||||
} else {
|
||||
let tok_lower = token.to_lowercase();
|
||||
symbol_to_id(&tok_lower, eth_tokenlist)
|
||||
}
|
||||
}
|
||||
_ => Err(Error::NotSupportedNetwork),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn symbol_to_id(token: &str, tokenlist: &TokenList) -> Result<String> {
|
||||
let vec: Vec<char> = token.chars().collect();
|
||||
let mut counter = 0;
|
||||
for c in vec {
|
||||
if c.is_alphabetic() {
|
||||
counter += 1;
|
||||
}
|
||||
}
|
||||
if counter == token.len() {
|
||||
if let Some(id) = tokenlist.search_id(token)? {
|
||||
Ok(id)
|
||||
} else {
|
||||
Err(Error::TokenParseError)
|
||||
}
|
||||
} else {
|
||||
Ok(token.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
258
src/error.rs
Normal file
258
src/error.rs
Normal file
@@ -0,0 +1,258 @@
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
#[derive(Debug, Clone, thiserror::Error)]
|
||||
pub enum Error {
|
||||
#[error("io error: `{0:?}`")]
|
||||
Io(std::io::ErrorKind),
|
||||
// #[error("Infallible Error: `{0}`")]
|
||||
// InfallibleError(String),
|
||||
|
||||
// #[error("Cannot find home directory")]
|
||||
// PathNotFound,
|
||||
#[cfg(feature = "util")]
|
||||
/// VarInt was encoded in a non-minimal way
|
||||
#[error("non-minimal varint")]
|
||||
NonMinimalVarInt,
|
||||
|
||||
#[cfg(feature = "util")]
|
||||
#[error("parse failed: `{0}`")]
|
||||
ParseFailed(&'static str),
|
||||
// #[error("decode failed: `{0}`")]
|
||||
// DecodeError(&'static str),
|
||||
// #[error("encode failed: `{0}`")]
|
||||
// EncodeError(&'static str),
|
||||
#[error(transparent)]
|
||||
ParseIntError(#[from] std::num::ParseIntError),
|
||||
|
||||
#[cfg(feature = "util")]
|
||||
#[error(transparent)]
|
||||
ParseBigIntError(#[from] num_bigint::ParseBigIntError),
|
||||
|
||||
// #[error(transparent)]
|
||||
// ParseFloatError(#[from] std::num::ParseFloatError),
|
||||
// #[error(transparent)]
|
||||
// FromHexError(#[from] hex::FromHexError),
|
||||
// #[error("Url parse error `{0}`")]
|
||||
// UrlParseError(String),
|
||||
// #[error("No url found")]
|
||||
// NoUrlFound,
|
||||
// #[error("Malformed packet")]
|
||||
// MalformedPacket,
|
||||
// #[error(transparent)]
|
||||
// AddrParseError(#[from] std::net::AddrParseError),
|
||||
// #[error(transparent)]
|
||||
// Base58EncodeError(#[from] bs58::encode::Error),
|
||||
// #[error(transparent)]
|
||||
// Base58DecodeError(#[from] bs58::decode::Error),
|
||||
#[error(transparent)]
|
||||
Utf8Error(#[from] std::string::FromUtf8Error),
|
||||
|
||||
#[error(transparent)]
|
||||
StrUtf8Error(#[from] std::str::Utf8Error),
|
||||
|
||||
// #[error("TryInto error")]
|
||||
// TryIntoError,
|
||||
// #[error("TryFrom error")]
|
||||
// TryFromError,
|
||||
// #[error(transparent)]
|
||||
// TryFromBigIntError(#[from] num_bigint::TryFromBigIntError<num_bigint::BigUint>),
|
||||
#[cfg(feature = "util")]
|
||||
#[error("Json serialization error: `{0}`")]
|
||||
SerdeJsonError(String),
|
||||
// #[error(transparent)]
|
||||
// TomlDeserializeError(#[from] toml::de::Error),
|
||||
// #[error(transparent)]
|
||||
// TomlSerializeError(#[from] toml::ser::Error),
|
||||
// #[error("Bincode serialization error: `{0}`")]
|
||||
// BincodeError(String),
|
||||
|
||||
// /// Contract
|
||||
// #[error("Bad variable ref type byte")]
|
||||
// BadVariableRefType,
|
||||
// #[error("Bad operation type byte")]
|
||||
// BadOperationType,
|
||||
// #[error("Bad constraint type byte")]
|
||||
// BadConstraintType,
|
||||
// #[error("Invalid param name")]
|
||||
// InvalidParamName,
|
||||
// #[error("Invalid param type")]
|
||||
// InvalidParamType,
|
||||
// #[error("Missing params")]
|
||||
// MissingParams,
|
||||
// #[error("Contract is poorly defined")]
|
||||
// BadContract,
|
||||
// #[error("Operation failed")]
|
||||
// OperationFailed,
|
||||
// #[error("PLONK error: `{0}`")]
|
||||
// PlonkError(String),
|
||||
// #[error("Unable to decrypt mint note")]
|
||||
// NoteDecryptionFailed,
|
||||
|
||||
// #[cfg(feature = "node")]
|
||||
// #[error(transparent)]
|
||||
// VerifyFailed(#[from] crate::node::state::VerifyFailed),
|
||||
// #[error("MerkleTree is full")]
|
||||
// TreeFull,
|
||||
|
||||
// /// Service
|
||||
// #[error("Services Error: `{0}`")]
|
||||
// ServicesError(&'static str),
|
||||
// #[error("Client failed: `{0}`")]
|
||||
// ClientFailed(String),
|
||||
// #[error("Cashier failed: `{0}`")]
|
||||
// CashierError(String),
|
||||
// #[error("ZmqError: `{0}`")]
|
||||
// ZmqError(String),
|
||||
|
||||
// /// Database/Sql errors
|
||||
// #[error("Rocksdb error: `{0}`")]
|
||||
// RocksdbError(String),
|
||||
// #[error("sqlx error: `{0}`")]
|
||||
// SqlxError(String),
|
||||
// #[error("SlabsStore Error: `{0}`")]
|
||||
// SlabsStore(String),
|
||||
|
||||
// /// RPC errors
|
||||
// #[error("JsonRpc Error: `{0}`")]
|
||||
// JsonRpcError(String),
|
||||
#[error("Not supported network")]
|
||||
NotSupportedNetwork,
|
||||
|
||||
#[error("Not supported token")]
|
||||
NotSupportedToken,
|
||||
|
||||
#[error("Could not parse token parameter")]
|
||||
TokenParseError,
|
||||
|
||||
// #[error("Cannot parse network parameter")]
|
||||
// NetworkParseError,
|
||||
// #[error("Async_Native_TLS error: `{0}`")]
|
||||
// AsyncNativeTlsError(String),
|
||||
// #[error("TungsteniteError: `{0}`")]
|
||||
// TungsteniteError(String),
|
||||
|
||||
// /// Network
|
||||
// #[error("Connection failed")]
|
||||
// ConnectFailed,
|
||||
// #[error("Connection timed out")]
|
||||
// ConnectTimeout,
|
||||
// #[error("Channel stopped")]
|
||||
// ChannelStopped,
|
||||
// #[error("Channel timed out")]
|
||||
// ChannelTimeout,
|
||||
// #[error("Service stopped")]
|
||||
// ServiceStopped,
|
||||
|
||||
// /// Util
|
||||
// #[error("No config file detected. Please create one.")]
|
||||
// ConfigNotFound,
|
||||
#[cfg(feature = "util")]
|
||||
#[error("No keypair file detected.")]
|
||||
KeypairPathNotFound,
|
||||
// #[error("SetLoggerError")]
|
||||
// SetLoggerError,
|
||||
// #[error("Async_channel sender error")]
|
||||
// AsyncChannelSenderError,
|
||||
// #[error(transparent)]
|
||||
// AsyncChannelReceiverError(#[from] async_channel::RecvError),
|
||||
|
||||
// /// Keypari & Address
|
||||
// #[error("Error converting Address to PublicKey")]
|
||||
// AddressToPublicKeyError,
|
||||
// #[error("Error converting bytes to PublicKey")]
|
||||
// PublicKeyFromBytes,
|
||||
// #[error("Error converting bytes to SecretKey")]
|
||||
// SecretKeyFromBytes,
|
||||
// #[error("Invalid Address")]
|
||||
// InvalidAddress,
|
||||
}
|
||||
|
||||
// #[cfg(feature = "node")]
|
||||
// impl From<zeromq::ZmqError> for Error {
|
||||
// fn from(err: zeromq::ZmqError) -> Error {
|
||||
// Error::ZmqError(err.to_string())
|
||||
// }
|
||||
// }
|
||||
|
||||
// #[cfg(feature = "chain")]
|
||||
// impl From<rocksdb::Error> for Error {
|
||||
// fn from(err: rocksdb::Error) -> Error {
|
||||
// Error::RocksdbError(err.to_string())
|
||||
// }
|
||||
// }
|
||||
|
||||
// #[cfg(feature = "node")]
|
||||
// impl From<sqlx::error::Error> for Error {
|
||||
// fn from(err: sqlx::error::Error) -> Error {
|
||||
// Error::SqlxError(err.to_string())
|
||||
// }
|
||||
// }
|
||||
|
||||
#[cfg(feature = "util")]
|
||||
impl From<serde_json::Error> for Error {
|
||||
fn from(err: serde_json::Error) -> Error {
|
||||
Error::SerdeJsonError(err.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "util")]
|
||||
impl From<std::io::Error> for Error {
|
||||
fn from(err: std::io::Error) -> Error {
|
||||
Error::Io(err.kind())
|
||||
}
|
||||
}
|
||||
|
||||
// impl<T> From<async_channel::SendError<T>> for Error {
|
||||
// fn from(_err: async_channel::SendError<T>) -> Error {
|
||||
// Error::AsyncChannelSenderError
|
||||
// }
|
||||
// }
|
||||
|
||||
// impl From<async_native_tls::Error> for Error {
|
||||
// fn from(err: async_native_tls::Error) -> Error {
|
||||
// Error::AsyncNativeTlsError(err.to_string())
|
||||
// }
|
||||
// }
|
||||
|
||||
// impl From<url::ParseError> for Error {
|
||||
// fn from(err: url::ParseError) -> Error {
|
||||
// Error::UrlParseError(err.to_string())
|
||||
// }
|
||||
// }
|
||||
|
||||
// #[cfg(feature = "node")]
|
||||
// impl From<crate::node::client::ClientFailed> for Error {
|
||||
// fn from(err: crate::node::client::ClientFailed) -> Error {
|
||||
// Error::ClientFailed(err.to_string())
|
||||
// }
|
||||
// }
|
||||
|
||||
// impl From<log::SetLoggerError> for Error {
|
||||
// fn from(_err: log::SetLoggerError) -> Error {
|
||||
// Error::SetLoggerError
|
||||
// }
|
||||
// }
|
||||
|
||||
// impl From<tungstenite::Error> for Error {
|
||||
// fn from(err: tungstenite::Error) -> Error {
|
||||
// Error::TungsteniteError(err.to_string())
|
||||
// }
|
||||
// }
|
||||
|
||||
// impl From<halo2::plonk::Error> for Error {
|
||||
// fn from(err: halo2::plonk::Error) -> Error {
|
||||
// Error::PlonkError(format!("{:?}", err))
|
||||
// }
|
||||
// }
|
||||
|
||||
// impl From<Box<bincode::ErrorKind>> for Error {
|
||||
// fn from(err: Box<bincode::ErrorKind>) -> Error {
|
||||
// Error::BincodeError(err.to_string())
|
||||
// }
|
||||
// }
|
||||
|
||||
// impl From<std::convert::Infallible> for Error {
|
||||
// fn from(err: std::convert::Infallible) -> Error {
|
||||
// Error::InfallibleError(err.to_string())
|
||||
// }
|
||||
// }
|
||||
22
src/lib.rs
22
src/lib.rs
@@ -1,8 +1,22 @@
|
||||
pub mod error;
|
||||
pub use error::{Error, Result};
|
||||
|
||||
#[cfg(feature = "cli")]
|
||||
pub mod cli;
|
||||
|
||||
#[cfg(feature = "crypto")]
|
||||
pub mod crypto;
|
||||
|
||||
#[cfg(feature = "net")]
|
||||
pub mod net;
|
||||
|
||||
#[cfg(feature = "system")]
|
||||
pub mod system;
|
||||
|
||||
#[cfg(feature = "crypto")]
|
||||
pub mod types;
|
||||
|
||||
#[cfg(feature = "crypto")]
|
||||
pub mod zk;
|
||||
|
||||
#[cfg(feature = "node")]
|
||||
@@ -17,10 +31,8 @@ pub mod tui;
|
||||
#[cfg(feature = "chain")]
|
||||
pub mod chain;
|
||||
|
||||
#[cfg(feature = "util")]
|
||||
pub mod util;
|
||||
|
||||
pub use util::{
|
||||
error,
|
||||
error::{Error, Result},
|
||||
serial,
|
||||
};
|
||||
#[cfg(feature = "rpc")]
|
||||
pub mod rpc;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use futures::prelude::*;
|
||||
|
||||
use super::{endian, serial::VarInt, Error, Result};
|
||||
use super::{endian, serial::VarInt};
|
||||
use crate::{Error, Result};
|
||||
|
||||
impl VarInt {
|
||||
pub async fn encode_async<W: AsyncWrite + Unpin>(&self, stream: &mut W) -> Result<usize> {
|
||||
|
||||
@@ -1,246 +0,0 @@
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
#[derive(Debug, Clone, thiserror::Error)]
|
||||
pub enum Error {
|
||||
#[error("io error: `{0:?}`")]
|
||||
Io(std::io::ErrorKind),
|
||||
|
||||
#[error("Infallible Error: `{0}`")]
|
||||
InfallibleError(String),
|
||||
|
||||
#[error("Cannot find home directory")]
|
||||
PathNotFound,
|
||||
/// VarInt was encoded in a non-minimal way
|
||||
#[error("non-minimal varint")]
|
||||
NonMinimalVarInt,
|
||||
|
||||
/// Parsing And Encode/Decode errors
|
||||
#[error("parse failed: `{0}`")]
|
||||
ParseFailed(&'static str),
|
||||
#[error("decode failed: `{0}`")]
|
||||
DecodeError(&'static str),
|
||||
#[error("encode failed: `{0}`")]
|
||||
EncodeError(&'static str),
|
||||
#[error(transparent)]
|
||||
ParseIntError(#[from] std::num::ParseIntError),
|
||||
#[error(transparent)]
|
||||
ParseBigIntError(#[from] num_bigint::ParseBigIntError),
|
||||
#[error(transparent)]
|
||||
ParseFloatError(#[from] std::num::ParseFloatError),
|
||||
#[error(transparent)]
|
||||
FromHexError(#[from] hex::FromHexError),
|
||||
#[error("Url parse error `{0}`")]
|
||||
UrlParseError(String),
|
||||
#[error("No url found")]
|
||||
NoUrlFound,
|
||||
#[error("Malformed packet")]
|
||||
MalformedPacket,
|
||||
#[error(transparent)]
|
||||
AddrParseError(#[from] std::net::AddrParseError),
|
||||
#[error(transparent)]
|
||||
Base58EncodeError(#[from] bs58::encode::Error),
|
||||
#[error(transparent)]
|
||||
Base58DecodeError(#[from] bs58::decode::Error),
|
||||
#[error(transparent)]
|
||||
Utf8Error(#[from] std::string::FromUtf8Error),
|
||||
#[error(transparent)]
|
||||
StrUtf8Error(#[from] std::str::Utf8Error),
|
||||
#[error("TryInto error")]
|
||||
TryIntoError,
|
||||
#[error("TryFrom error")]
|
||||
TryFromError,
|
||||
#[error(transparent)]
|
||||
TryFromBigIntError(#[from] num_bigint::TryFromBigIntError<num_bigint::BigUint>),
|
||||
#[error("Json serialization error: `{0}`")]
|
||||
SerdeJsonError(String),
|
||||
#[error(transparent)]
|
||||
TomlDeserializeError(#[from] toml::de::Error),
|
||||
#[error(transparent)]
|
||||
TomlSerializeError(#[from] toml::ser::Error),
|
||||
#[error("Bincode serialization error: `{0}`")]
|
||||
BincodeError(String),
|
||||
|
||||
/// Contract
|
||||
#[error("Bad variable ref type byte")]
|
||||
BadVariableRefType,
|
||||
#[error("Bad operation type byte")]
|
||||
BadOperationType,
|
||||
#[error("Bad constraint type byte")]
|
||||
BadConstraintType,
|
||||
#[error("Invalid param name")]
|
||||
InvalidParamName,
|
||||
#[error("Invalid param type")]
|
||||
InvalidParamType,
|
||||
#[error("Missing params")]
|
||||
MissingParams,
|
||||
#[error("Contract is poorly defined")]
|
||||
BadContract,
|
||||
#[error("Operation failed")]
|
||||
OperationFailed,
|
||||
#[error("PLONK error: `{0}`")]
|
||||
PlonkError(String),
|
||||
#[error("Unable to decrypt mint note")]
|
||||
NoteDecryptionFailed,
|
||||
|
||||
#[cfg(feature = "node")]
|
||||
#[error(transparent)]
|
||||
VerifyFailed(#[from] crate::node::state::VerifyFailed),
|
||||
#[error("MerkleTree is full")]
|
||||
TreeFull,
|
||||
|
||||
/// Service
|
||||
#[error("Services Error: `{0}`")]
|
||||
ServicesError(&'static str),
|
||||
#[error("Client failed: `{0}`")]
|
||||
ClientFailed(String),
|
||||
#[error("Cashier failed: `{0}`")]
|
||||
CashierError(String),
|
||||
#[error("ZmqError: `{0}`")]
|
||||
ZmqError(String),
|
||||
|
||||
/// Database/Sql errors
|
||||
#[error("Rocksdb error: `{0}`")]
|
||||
RocksdbError(String),
|
||||
#[error("sqlx error: `{0}`")]
|
||||
SqlxError(String),
|
||||
#[error("SlabsStore Error: `{0}`")]
|
||||
SlabsStore(String),
|
||||
|
||||
/// RPC errors
|
||||
#[error("JsonRpc Error: `{0}`")]
|
||||
JsonRpcError(String),
|
||||
#[error("Not supported network")]
|
||||
NotSupportedNetwork,
|
||||
#[error("Not supported token")]
|
||||
NotSupportedToken,
|
||||
#[error("Could not parse token parameter")]
|
||||
TokenParseError,
|
||||
#[error("Cannot parse network parameter")]
|
||||
NetworkParseError,
|
||||
#[error("Async_Native_TLS error: `{0}`")]
|
||||
AsyncNativeTlsError(String),
|
||||
#[error("TungsteniteError: `{0}`")]
|
||||
TungsteniteError(String),
|
||||
|
||||
/// Network
|
||||
#[error("Connection failed")]
|
||||
ConnectFailed,
|
||||
#[error("Connection timed out")]
|
||||
ConnectTimeout,
|
||||
#[error("Channel stopped")]
|
||||
ChannelStopped,
|
||||
#[error("Channel timed out")]
|
||||
ChannelTimeout,
|
||||
#[error("Service stopped")]
|
||||
ServiceStopped,
|
||||
|
||||
/// Util
|
||||
#[error("No config file detected. Please create one.")]
|
||||
ConfigNotFound,
|
||||
#[error("No keypair file detected.")]
|
||||
KeypairPathNotFound,
|
||||
#[error("SetLoggerError")]
|
||||
SetLoggerError,
|
||||
#[error("Async_channel sender error")]
|
||||
AsyncChannelSenderError,
|
||||
#[error(transparent)]
|
||||
AsyncChannelReceiverError(#[from] async_channel::RecvError),
|
||||
|
||||
/// Keypari & Address
|
||||
#[error("Error converting Address to PublicKey")]
|
||||
AddressToPublicKeyError,
|
||||
#[error("Error converting bytes to PublicKey")]
|
||||
PublicKeyFromBytes,
|
||||
#[error("Error converting bytes to SecretKey")]
|
||||
SecretKeyFromBytes,
|
||||
#[error("Invalid Address")]
|
||||
InvalidAddress,
|
||||
}
|
||||
|
||||
#[cfg(feature = "node")]
|
||||
impl From<zeromq::ZmqError> for Error {
|
||||
fn from(err: zeromq::ZmqError) -> Error {
|
||||
Error::ZmqError(err.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "chain")]
|
||||
impl From<rocksdb::Error> for Error {
|
||||
fn from(err: rocksdb::Error) -> Error {
|
||||
Error::RocksdbError(err.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "node")]
|
||||
impl From<sqlx::error::Error> for Error {
|
||||
fn from(err: sqlx::error::Error) -> Error {
|
||||
Error::SqlxError(err.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<serde_json::Error> for Error {
|
||||
fn from(err: serde_json::Error) -> Error {
|
||||
Error::SerdeJsonError(err.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<std::io::Error> for Error {
|
||||
fn from(err: std::io::Error) -> Error {
|
||||
Error::Io(err.kind())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> From<async_channel::SendError<T>> for Error {
|
||||
fn from(_err: async_channel::SendError<T>) -> Error {
|
||||
Error::AsyncChannelSenderError
|
||||
}
|
||||
}
|
||||
|
||||
impl From<async_native_tls::Error> for Error {
|
||||
fn from(err: async_native_tls::Error) -> Error {
|
||||
Error::AsyncNativeTlsError(err.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<url::ParseError> for Error {
|
||||
fn from(err: url::ParseError) -> Error {
|
||||
Error::UrlParseError(err.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "node")]
|
||||
impl From<crate::node::client::ClientFailed> for Error {
|
||||
fn from(err: crate::node::client::ClientFailed) -> Error {
|
||||
Error::ClientFailed(err.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<log::SetLoggerError> for Error {
|
||||
fn from(_err: log::SetLoggerError) -> Error {
|
||||
Error::SetLoggerError
|
||||
}
|
||||
}
|
||||
|
||||
impl From<tungstenite::Error> for Error {
|
||||
fn from(err: tungstenite::Error) -> Error {
|
||||
Error::TungsteniteError(err.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<halo2::plonk::Error> for Error {
|
||||
fn from(err: halo2::plonk::Error) -> Error {
|
||||
Error::PlonkError(format!("{:?}", err))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Box<bincode::ErrorKind>> for Error {
|
||||
fn from(err: Box<bincode::ErrorKind>) -> Error {
|
||||
Error::BincodeError(err.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<std::convert::Infallible> for Error {
|
||||
fn from(err: std::convert::Infallible) -> Error {
|
||||
Error::InfallibleError(err.to_string())
|
||||
}
|
||||
}
|
||||
@@ -1,23 +1,12 @@
|
||||
pub mod address;
|
||||
pub mod async_serial;
|
||||
pub mod async_util;
|
||||
pub mod endian;
|
||||
pub mod error;
|
||||
pub mod loader;
|
||||
pub mod net_name;
|
||||
pub mod parse;
|
||||
pub mod path;
|
||||
pub mod rpc;
|
||||
pub mod serial;
|
||||
pub mod token_list;
|
||||
|
||||
pub use async_util::sleep;
|
||||
pub use loader::ContractLoader;
|
||||
pub use net_name::NetworkName;
|
||||
pub use parse::{assign_id, decode_base10, encode_base10, generate_id, generate_id2};
|
||||
pub use parse::{decode_base10, encode_base10};
|
||||
pub use path::{expand_path, join_config_path, load_keypair_to_str};
|
||||
pub use token_list::{DrkTokenList, TokenList};
|
||||
|
||||
pub use address::Address;
|
||||
|
||||
pub use error::{Error, Result};
|
||||
|
||||
@@ -3,7 +3,7 @@ use std::str::FromStr;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{
|
||||
serial::{Decodable, Encodable},
|
||||
util::serial::{Decodable, Encodable},
|
||||
Result,
|
||||
};
|
||||
|
||||
|
||||
@@ -1,138 +1,8 @@
|
||||
use std::{iter::FromIterator, str::FromStr};
|
||||
|
||||
use num_bigint::BigUint;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use crate::{
|
||||
serial::{deserialize, serialize},
|
||||
types::*,
|
||||
util::{NetworkName, TokenList},
|
||||
Error, Result,
|
||||
};
|
||||
|
||||
pub const ETH_NATIVE_TOKEN_ID: &str = "0x0000000000000000000000000000000000000000";
|
||||
|
||||
// hash the external token ID and NetworkName param.
|
||||
// if fails, change the last 4 bytes and hash it again. keep repeating until it works.
|
||||
pub fn generate_id(tkn_str: &str, network: &NetworkName) -> Result<DrkTokenId> {
|
||||
let mut id_string = network.to_string();
|
||||
|
||||
id_string.push_str(tkn_str);
|
||||
|
||||
let mut data: Vec<u8> = serialize(&id_string);
|
||||
|
||||
let token_id = match deserialize::<DrkTokenId>(&data) {
|
||||
Ok(v) => v,
|
||||
Err(_) => {
|
||||
let mut counter = 0;
|
||||
loop {
|
||||
data.truncate(28);
|
||||
let serialized_counter = serialize(&counter);
|
||||
data.extend(serialized_counter.iter());
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(&data);
|
||||
let hash = hasher.finalize();
|
||||
let token_id = deserialize::<DrkTokenId>(&hash);
|
||||
if token_id.is_err() {
|
||||
counter += 1;
|
||||
continue
|
||||
}
|
||||
return Ok(token_id.unwrap())
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Ok(token_id)
|
||||
}
|
||||
|
||||
// YOLO
|
||||
pub fn generate_id2(tkn_str: &str, network: &NetworkName) -> Result<DrkTokenId> {
|
||||
let mut num = 0_u64;
|
||||
|
||||
match network {
|
||||
NetworkName::Solana => {
|
||||
for i in ['s', 'o', 'l'] {
|
||||
num += i as u64;
|
||||
}
|
||||
}
|
||||
NetworkName::Bitcoin => {
|
||||
for i in ['b', 't', 'c'] {
|
||||
num += i as u64;
|
||||
}
|
||||
}
|
||||
NetworkName::Ethereum => {
|
||||
for i in ['e', 't', 'h'] {
|
||||
num += i as u64;
|
||||
}
|
||||
}
|
||||
NetworkName::Empty => unimplemented!(),
|
||||
}
|
||||
|
||||
for i in tkn_str.chars() {
|
||||
num += i as u64;
|
||||
}
|
||||
|
||||
Ok(DrkTokenId::from(num))
|
||||
}
|
||||
|
||||
pub fn assign_id(
|
||||
network: &NetworkName,
|
||||
token: &str,
|
||||
sol_tokenlist: &TokenList,
|
||||
eth_tokenlist: &TokenList,
|
||||
btc_tokenlist: &TokenList,
|
||||
) -> Result<String> {
|
||||
match network {
|
||||
NetworkName::Solana => {
|
||||
// (== 44) can represent a Solana base58 token mint address
|
||||
if token.len() == 44 {
|
||||
Ok(token.to_string())
|
||||
} else {
|
||||
let tok_lower = token.to_lowercase();
|
||||
symbol_to_id(&tok_lower, sol_tokenlist)
|
||||
}
|
||||
}
|
||||
NetworkName::Bitcoin => {
|
||||
if token.len() == 34 {
|
||||
Ok(token.to_string())
|
||||
} else {
|
||||
let tok_lower = token.to_lowercase();
|
||||
symbol_to_id(&tok_lower, btc_tokenlist)
|
||||
}
|
||||
}
|
||||
NetworkName::Ethereum => {
|
||||
// (== 42) can represent a erc20 token mint address
|
||||
if token.len() == 42 {
|
||||
Ok(token.to_string())
|
||||
} else if token == "eth" {
|
||||
Ok(ETH_NATIVE_TOKEN_ID.to_string())
|
||||
} else {
|
||||
let tok_lower = token.to_lowercase();
|
||||
symbol_to_id(&tok_lower, eth_tokenlist)
|
||||
}
|
||||
}
|
||||
_ => Err(Error::NotSupportedNetwork),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn symbol_to_id(token: &str, tokenlist: &TokenList) -> Result<String> {
|
||||
let vec: Vec<char> = token.chars().collect();
|
||||
let mut counter = 0;
|
||||
for c in vec {
|
||||
if c.is_alphabetic() {
|
||||
counter += 1;
|
||||
}
|
||||
}
|
||||
if counter == token.len() {
|
||||
if let Some(id) = tokenlist.search_id(token)? {
|
||||
Ok(id)
|
||||
} else {
|
||||
Err(Error::TokenParseError)
|
||||
}
|
||||
} else {
|
||||
Ok(token.to_string())
|
||||
}
|
||||
}
|
||||
use crate::{Error, Result};
|
||||
|
||||
fn is_digit(c: char) -> bool {
|
||||
('0'..='9').contains(&c)
|
||||
|
||||
@@ -8,10 +8,8 @@ use std::{
|
||||
|
||||
use num_bigint::BigUint;
|
||||
|
||||
use super::{
|
||||
endian,
|
||||
error::{Error, Result},
|
||||
};
|
||||
use super::endian;
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// Encode an object into a vector
|
||||
pub fn serialize<T: Encodable + ?Sized>(data: &T) -> Vec<u8> {
|
||||
|
||||
Reference in New Issue
Block a user