Skip to content

Commit

Permalink
feat(cosmos): komodo-defi-proxy support (#2173)
Browse files Browse the repository at this point in the history
This commit does the following:
* Adds new signature algorithm for komodo-defi-proxy (coin-agnostic, pubkey-only mode)
* Refactors NFT and ETH proxy to use the new algorithm
* Implements proxy support for Tendermint (including WebSocket connections)

BREAKING CHANGES:
* Updates to Tendermint activation payloads:
  - 'rpc_urls' field (previously a list of plain string values) is replaced with 'nodes' (a list of JSON objects).
* All RPC methods fields controlling komodo-defi-proxy are renamed to 'komodo_proxy', this affects various activations, including ETH/EVM.
  • Loading branch information
onur-ozkan authored Aug 15, 2024
1 parent 7723b50 commit 8b1170d
Show file tree
Hide file tree
Showing 32 changed files with 611 additions and 483 deletions.
13 changes: 13 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ members = [
"mm2src/mm2_p2p",
"mm2src/mm2_rpc",
"mm2src/mm2_state_machine",
"mm2src/proxy_signature",
"mm2src/rpc_task",
"mm2src/trezor",
]
Expand Down
1 change: 1 addition & 0 deletions mm2src/coins/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ parking_lot = { version = "0.12.0", features = ["nightly"] }
primitives = { path = "../mm2_bitcoin/primitives" }
prost = "0.11"
protobuf = "2.20"
proxy_signature = { path = "../proxy_signature" }
rand = { version = "0.7", features = ["std", "small_rng"] }
regex = "1"
reqwest = { version = "0.11.9", default-features = false, features = ["json"], optional = true }
Expand Down
55 changes: 6 additions & 49 deletions mm2src/coins/eth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ use common::executor::{abortable_queue::AbortableQueue, AbortOnDropHandle, Abort
AbortedError, SpawnAbortable, Timer};
use common::log::{debug, error, info, warn};
use common::number_type_casting::SafeTypeCastingNumbers;
use common::{get_utc_timestamp, now_sec, small_rng, DEX_FEE_ADDR_RAW_PUBKEY};
use common::{now_sec, small_rng, DEX_FEE_ADDR_RAW_PUBKEY};
use crypto::privkey::key_pair_from_secret;
use crypto::{Bip44Chain, CryptoCtx, CryptoCtxError, GlobalHDAccountArc, KeyPairPolicy};
use derive_more::Display;
Expand All @@ -78,7 +78,6 @@ use http::Uri;
use instant::Instant;
use mm2_core::mm_ctx::{MmArc, MmWeak};
use mm2_event_stream::behaviour::{EventBehaviour, EventInitStatus};
use mm2_net::transport::{KomodefiProxyAuthValidation, ProxyAuthValidationGenerator};
use mm2_number::bigdecimal_custom::CheckedDivision;
use mm2_number::{BigDecimal, BigUint, MmNumber};
#[cfg(test)] use mocktopus::macros::*;
Expand Down Expand Up @@ -292,9 +291,6 @@ impl Default for EthGasLimit {
}
}

/// Lifetime of generated signed message for proxy-auth requests
const PROXY_AUTH_SIGNED_MESSAGE_LIFETIME_SEC: i64 = 90;

/// Max transaction type according to EIP-2718
const ETH_MAX_TX_TYPE: u64 = 0x7f;

Expand Down Expand Up @@ -5790,45 +5786,6 @@ impl<T: TryToAddress> TryToAddress for Option<T> {
}
}

pub trait KomodoDefiAuthMessages {
fn proxy_auth_sign_message_hash(message: String) -> Option<[u8; 32]>;
fn generate_proxy_auth_signed_validation(
generator: ProxyAuthValidationGenerator,
) -> SignatureResult<KomodefiProxyAuthValidation>;
}

impl KomodoDefiAuthMessages for EthCoin {
fn proxy_auth_sign_message_hash(message: String) -> Option<[u8; 32]> {
let message_prefix = "atomicDEX Auth Ethereum Signed Message:\n";
let prefix_len = CompactInteger::from(message_prefix.len());

let mut stream = Stream::new();
prefix_len.serialize(&mut stream);
stream.append_slice(message_prefix.as_bytes());
stream.append_slice(message.len().to_string().as_bytes());
stream.append_slice(message.as_bytes());

Some(keccak256(&stream.out()).take())
}

fn generate_proxy_auth_signed_validation(
generator: ProxyAuthValidationGenerator,
) -> SignatureResult<KomodefiProxyAuthValidation> {
let timestamp_message = get_utc_timestamp() + PROXY_AUTH_SIGNED_MESSAGE_LIFETIME_SEC;

let message_hash = EthCoin::proxy_auth_sign_message_hash(timestamp_message.to_string())
.ok_or(SignatureError::PrefixNotFound)?;
let signature = sign(&generator.secret, &H256::from(message_hash))?;

Ok(KomodefiProxyAuthValidation {
coin_ticker: generator.coin_ticker,
address: generator.address,
timestamp_message,
signature: format!("0x{}", signature),
})
}
}

fn validate_fee_impl(coin: EthCoin, validate_fee_args: EthValidateFeeArgs<'_>) -> ValidatePaymentFut<()> {
let fee_tx_hash = validate_fee_args.fee_tx_hash.to_owned();
let sender_addr = try_f!(
Expand Down Expand Up @@ -6282,10 +6239,7 @@ pub async fn eth_coin_from_conf_and_request(
Some("ws") | Some("wss") => {
const TMP_SOCKET_CONNECTION: Duration = Duration::from_secs(20);

let node = WebsocketTransportNode {
uri: uri.clone(),
gui_auth: false,
};
let node = WebsocketTransportNode { uri: uri.clone() };
let websocket_transport = WebsocketTransport::with_event_handlers(node, event_handlers.clone());

// Temporarily start the connection loop (we close the connection once we have the client version below).
Expand All @@ -6300,7 +6254,10 @@ pub async fn eth_coin_from_conf_and_request(
Web3Transport::Websocket(websocket_transport)
},
Some("http") | Some("https") => {
let node = HttpTransportNode { uri, gui_auth: false };
let node = HttpTransportNode {
uri,
komodo_proxy: false,
};

Web3Transport::new_http_with_event_handlers(node, event_handlers.clone())
},
Expand Down
2 changes: 1 addition & 1 deletion mm2src/coins/eth/for_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ pub(crate) fn eth_coin_from_keypair(
for url in urls.iter() {
let node = HttpTransportNode {
uri: url.parse().unwrap(),
gui_auth: false,
komodo_proxy: false,
};
let transport = Web3Transport::new_http(node);
let web3 = Web3::new(transport);
Expand Down
Loading

0 comments on commit 8b1170d

Please sign in to comment.