|
| 1 | +//! `rand perp …` against a loopback node: the offline helpers (keygen, genesis-root, image-hc), |
| 2 | +//! the reads, and the signed submissions (order, cancel, withdraw, oracle), whose transactions |
| 3 | +//! are captured off the wire and decoded. None of these proves anything. Chain 14 is one of the |
| 4 | +//! chains cut before `binding_domain`, so no genesis hash is needed to sign. |
| 5 | +
|
| 6 | +mod common; |
| 7 | + |
| 8 | +use common::*; |
| 9 | +use randprotocol_core::ledger::perps::account_id; |
| 10 | +use randprotocol_core::notes::word8_to_hex; |
| 11 | +use randprotocol_core::{Action, Transaction}; |
| 12 | +use serde_json::{json, Value}; |
| 13 | + |
| 14 | +fn sent(node: &Fake) -> Vec<Transaction> { |
| 15 | + node.calls |
| 16 | + .lock() |
| 17 | + .unwrap() |
| 18 | + .iter() |
| 19 | + .filter(|(m, _)| m == "rand_sendTransaction") |
| 20 | + .map(|(_, p)| Transaction::decode(&hex::decode(p[0].as_str().unwrap()).unwrap()).unwrap()) |
| 21 | + .collect() |
| 22 | +} |
| 23 | + |
| 24 | +fn perps_state() -> Value { |
| 25 | + json!({ |
| 26 | + "enabled": true, "collateral_asset": 0, "max_tier": 18, "max_window_blocks": 8, |
| 27 | + "engine_hc": "00".repeat(32), "proved_root": "11".repeat(32), "proved_height": 5, |
| 28 | + }) |
| 29 | +} |
| 30 | + |
| 31 | +fn trading_node(account_nonce: Option<u64>) -> Fake { |
| 32 | + fake(Box::new(move |m, _| match m { |
| 33 | + "rand_chainId" => Ok(json!(14)), |
| 34 | + "rand_getPerps" => Ok(perps_state()), |
| 35 | + "rand_getHead" => Ok(json!({ "height": 40 })), |
| 36 | + "rand_getPerpAccount" => Ok(match account_nonce { |
| 37 | + Some(n) => json!({ "account": "00", "trading_key": "00", "nonce_high": n.to_string() }), |
| 38 | + None => Value::Null, |
| 39 | + }), |
| 40 | + "rand_sendTransaction" => Ok(json!("ab".repeat(32))), |
| 41 | + _ => Err((-32601, "method not found".into())), |
| 42 | + })) |
| 43 | +} |
| 44 | + |
| 45 | +#[test] |
| 46 | +fn perp_keygen_writes_a_trading_key_once_and_prints_its_account() { |
| 47 | + let dir = tempfile::tempdir().unwrap(); |
| 48 | + let key = keygen(&dir); |
| 49 | + let out = dir.path().join("trade.json"); |
| 50 | + let r = rand(DEAD, &key, &["perp", "keygen", "--out", out.to_str().unwrap()]); |
| 51 | + assert!(r.ok, "{}", r.err); |
| 52 | + let kp = randprotocol_client::perps::load_dilithium_key(&out).unwrap(); |
| 53 | + assert_eq!(r.out, format!("wrote {}\naccount: {}\n", out.display(), word8_to_hex(&account_id(kp.public_key())))); |
| 54 | + let again = rand(DEAD, &key, &["perp", "keygen", "--out", out.to_str().unwrap()]); |
| 55 | + assert!(!again.ok, "an existing trading key is never overwritten"); |
| 56 | + #[cfg(unix)] |
| 57 | + { |
| 58 | + use std::os::unix::fs::PermissionsExt; |
| 59 | + assert_eq!(std::fs::metadata(&out).unwrap().permissions().mode() & 0o777, 0o600); |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +#[test] |
| 64 | +fn perp_genesis_root_and_image_hc_agree_with_the_library() { |
| 65 | + let dir = tempfile::tempdir().unwrap(); |
| 66 | + let key = dir.path().join("k.json"); |
| 67 | + let words = dir.path().join("state.json"); |
| 68 | + std::fs::write(&words, "[1,2,3,4]").unwrap(); |
| 69 | + let r = rand(DEAD, &key, &["perp", "genesis-root", "--state", words.to_str().unwrap()]); |
| 70 | + assert!(r.ok, "{}", r.err); |
| 71 | + assert_eq!(r.out.trim(), word8_to_hex(&randprotocol_client::perps::genesis_root(&[1, 2, 3, 4]))); |
| 72 | + std::fs::write(&words, "[1,2,3,5]").unwrap(); |
| 73 | + let r2 = rand(DEAD, &key, &["perp", "genesis-root", "--state", words.to_str().unwrap()]); |
| 74 | + assert_ne!(r.out, r2.out, "the root binds the words"); |
| 75 | + std::fs::write(&words, "{\"not\":\"an array\"}").unwrap(); |
| 76 | + let bad = rand(DEAD, &key, &["perp", "genesis-root", "--state", words.to_str().unwrap()]); |
| 77 | + assert!(!bad.ok && bad.err.contains("is not a JSON array of u32 words"), "{}", bad.err); |
| 78 | + |
| 79 | + let program = randprotocol_zkvm::guests::fib(5); |
| 80 | + let image = dir.path().join("engine.bin"); |
| 81 | + std::fs::write(&image, randprotocol_zkvm::codec::program_to_bytes(&program)).unwrap(); |
| 82 | + let hc = rand(DEAD, &key, &["perp", "image-hc", "--image", image.to_str().unwrap()]); |
| 83 | + assert!(hc.ok, "{}", hc.err); |
| 84 | + assert_eq!(hc.out.trim(), word8_to_hex(&randprotocol_client::perps::image_hc(&program))); |
| 85 | + std::fs::write(&image, b"xx").unwrap(); |
| 86 | + let junk = rand(DEAD, &key, &["perp", "image-hc", "--image", image.to_str().unwrap()]); |
| 87 | + assert!(!junk.ok && junk.err.contains("is not a program image"), "{}", junk.err); |
| 88 | + let absent = rand(DEAD, &key, &["perp", "image-hc", "--image", dir.path().join("nope").to_str().unwrap()]); |
| 89 | + assert!(!absent.ok && absent.err.contains("reading the engine image"), "{}", absent.err); |
| 90 | +} |
| 91 | + |
| 92 | +#[test] |
| 93 | +fn perp_state_account_and_inputs_read_the_node() { |
| 94 | + let dir = tempfile::tempdir().unwrap(); |
| 95 | + let key = dir.path().join("k.json"); |
| 96 | + let trade = dir.path().join("t.json"); |
| 97 | + assert!(rand(DEAD, &key, &["perp", "keygen", "--out", trade.to_str().unwrap()]).ok); |
| 98 | + let id = word8_to_hex(&account_id(randprotocol_client::perps::load_dilithium_key(&trade).unwrap().public_key())); |
| 99 | + let known = id.clone(); |
| 100 | + let node = fake(Box::new(move |m, p| match m { |
| 101 | + "rand_getPerps" => Ok(perps_state()), |
| 102 | + "rand_getPerpAccount" if p[0] == json!(known) => Ok(json!({ "account": known, "nonce_high": 3 })), |
| 103 | + "rand_getPerpAccount" => Ok(Value::Null), |
| 104 | + "rand_getPerpInputs" if p[0] == json!(9) => Ok(json!({ "words": [1, 2] })), |
| 105 | + "rand_getPerpInputs" => Ok(Value::Null), |
| 106 | + _ => Err((-32601, "method not found".into())), |
| 107 | + })); |
| 108 | + let state: Value = serde_json::from_str(&rand(&node.url, &key, &["perp", "state"]).out).unwrap(); |
| 109 | + assert_eq!(state["max_tier"], 18); |
| 110 | + let by_id = rand(&node.url, &key, &["perp", "account", &id]); |
| 111 | + assert_eq!(serde_json::from_str::<Value>(&by_id.out).unwrap()["nonce_high"], 3, "{}", by_id.err); |
| 112 | + let by_key = rand(&node.url, &key, &["perp", "account", "--trading-key", trade.to_str().unwrap()]); |
| 113 | + assert_eq!(by_key.out, by_id.out); |
| 114 | + let none = "07".repeat(32); |
| 115 | + assert_eq!(rand(&node.url, &key, &["perp", "account", &none]).out.trim(), format!("no account {none}")); |
| 116 | + let neither = rand(&node.url, &key, &["perp", "account"]); |
| 117 | + assert!(!neither.ok && neither.err.contains("name the account"), "{}", neither.err); |
| 118 | + assert_eq!(serde_json::from_str::<Value>(&rand(&node.url, &key, &["perp", "inputs", "9"]).out).unwrap()["words"], json!([1, 2])); |
| 119 | + assert_eq!(rand(&node.url, &key, &["perp", "inputs", "10"]).out.trim(), "no perp inputs at height 10"); |
| 120 | +} |
| 121 | + |
| 122 | +#[test] |
| 123 | +fn perp_state_on_a_chain_without_perps_is_named_by_the_actions() { |
| 124 | + let node = fake(Box::new(|m, _| match m { |
| 125 | + "rand_getPerps" => Ok(json!({ "enabled": false })), |
| 126 | + "rand_chainId" => Ok(json!(14)), |
| 127 | + "rand_getHead" => Ok(json!({ "height": 1 })), |
| 128 | + _ => Err((-32601, "method not found".into())), |
| 129 | + })); |
| 130 | + let dir = tempfile::tempdir().unwrap(); |
| 131 | + let key = keygen(&dir); |
| 132 | + let trade = dir.path().join("t.json"); |
| 133 | + assert!(rand(DEAD, &key, &["perp", "keygen", "--out", trade.to_str().unwrap()]).ok); |
| 134 | + let r = rand(&node.url, &key, &["perp", "withdraw", "--trading-key", trade.to_str().unwrap(), "--amount", "5"]); |
| 135 | + assert!(!r.ok && r.err.contains("this chain has no perps section"), "{}", r.err); |
| 136 | +} |
| 137 | + |
| 138 | +#[test] |
| 139 | +fn perp_order_signs_and_submits_with_the_next_nonce() { |
| 140 | + let dir = tempfile::tempdir().unwrap(); |
| 141 | + let key = keygen(&dir); |
| 142 | + let trade = dir.path().join("t.json"); |
| 143 | + assert!(rand(DEAD, &key, &["perp", "keygen", "--out", trade.to_str().unwrap()]).ok); |
| 144 | + let kp = randprotocol_client::perps::load_dilithium_key(&trade).unwrap(); |
| 145 | + let account = account_id(kp.public_key()); |
| 146 | + |
| 147 | + let node = trading_node(Some(6)); |
| 148 | + let t = trade.to_str().unwrap(); |
| 149 | + let r = rand(&node.url, &key, &["perp", "order", "--trading-key", t, "--market", "2", "--side", "sell", "--size", "10", "--price", "500", "--tif", "post", "--reduce-only", "--no-wait"]); |
| 150 | + assert!(r.ok, "{}", r.err); |
| 151 | + assert_eq!(r.out, format!("order {}\naccount {} nonce 7\n", "ab".repeat(32), word8_to_hex(&account))); |
| 152 | + let txs = sent(&node); |
| 153 | + assert_eq!(txs.len(), 1); |
| 154 | + assert_eq!(txs[0].chain_id, 14); |
| 155 | + assert!(txs[0].bundle.is_none(), "a perp order rides no bundle"); |
| 156 | + match &txs[0].action { |
| 157 | + Action::PerpOrder { account: a, body, signature } => { |
| 158 | + assert_eq!(*a, account); |
| 159 | + assert_eq!((body.nonce, body.market, body.side, body.kind, body.tif, body.reduce_only, body.price, body.size), (7, 2, 1, 0, 2, true, 500, 10)); |
| 160 | + assert!(*signature != randprotocol_core::Signature::empty(), "the order is signed"); |
| 161 | + } |
| 162 | + other => panic!("not an order: {other:?}"), |
| 163 | + } |
| 164 | + |
| 165 | + // A fresh account starts at nonce 1; an explicit --nonce is used as given and skips the lookup. |
| 166 | + let fresh = trading_node(None); |
| 167 | + let r = rand(&fresh.url, &key, &["perp", "order", "--trading-key", t, "--market", "1", "--side", "buy", "--size", "1", "--kind", "market", "--no-wait"]); |
| 168 | + assert!(r.ok && r.out.contains("nonce 1"), "{}{}", r.out, r.err); |
| 169 | + let r = rand(&fresh.url, &key, &["perp", "order", "--trading-key", t, "--market", "1", "--side", "buy", "--size", "1", "--kind", "market", "--nonce", "99", "--no-wait"]); |
| 170 | + assert!(r.ok && r.out.contains("nonce 99"), "{}", r.out); |
| 171 | + assert_eq!(fresh.methods().iter().filter(|m| *m == "rand_getPerpAccount").count(), 1, "--nonce skips the account lookup"); |
| 172 | +} |
| 173 | + |
| 174 | +#[test] |
| 175 | +fn perp_order_refuses_malformed_arguments_before_any_submission() { |
| 176 | + let dir = tempfile::tempdir().unwrap(); |
| 177 | + let key = keygen(&dir); |
| 178 | + let trade = dir.path().join("t.json"); |
| 179 | + assert!(rand(DEAD, &key, &["perp", "keygen", "--out", trade.to_str().unwrap()]).ok); |
| 180 | + let t = trade.to_str().unwrap(); |
| 181 | + let node = trading_node(None); |
| 182 | + for (extra, want) in [ |
| 183 | + (vec!["--side", "up", "--size", "1", "--price", "5"], "--side up: buy or sell"), |
| 184 | + (vec!["--side", "buy", "--size", "1", "--price", "5", "--kind", "stop"], "--kind stop: limit or market"), |
| 185 | + (vec!["--side", "buy", "--size", "1", "--price", "5", "--tif", "fok"], "--tif fok: gtc, ioc or post"), |
| 186 | + (vec!["--side", "buy", "--size", "1"], "a limit order needs --price"), |
| 187 | + (vec!["--side", "buy", "--size", "1", "--kind", "market", "--price", "5"], "a market order takes no --price"), |
| 188 | + (vec!["--side", "buy", "--size", "0", "--price", "5"], "--size 0 orders nothing"), |
| 189 | + ] { |
| 190 | + let mut args = vec!["perp", "order", "--trading-key", t, "--market", "1", "--no-wait"]; |
| 191 | + args.extend(extra.iter()); |
| 192 | + let r = rand(&node.url, &key, &args); |
| 193 | + assert!(!r.ok, "{extra:?}"); |
| 194 | + assert!(r.err.contains(want), "{extra:?}: {}", r.err); |
| 195 | + } |
| 196 | + assert!(sent(&node).is_empty(), "nothing was submitted"); |
| 197 | +} |
| 198 | + |
| 199 | +#[test] |
| 200 | +fn perp_cancel_submits_a_cancel_of_the_target() { |
| 201 | + let dir = tempfile::tempdir().unwrap(); |
| 202 | + let key = keygen(&dir); |
| 203 | + let trade = dir.path().join("t.json"); |
| 204 | + assert!(rand(DEAD, &key, &["perp", "keygen", "--out", trade.to_str().unwrap()]).ok); |
| 205 | + let node = trading_node(Some(2)); |
| 206 | + let r = rand(&node.url, &key, &["perp", "cancel", "--trading-key", trade.to_str().unwrap(), "--target", "2", "--no-wait"]); |
| 207 | + assert!(r.ok, "{}", r.err); |
| 208 | + assert!(r.out.contains("cancel ") && r.out.trim_end().ends_with("nonce 3 target 2"), "{}", r.out); |
| 209 | + assert!(matches!(sent(&node)[0].action, Action::PerpCancel { .. })); |
| 210 | +} |
| 211 | + |
| 212 | +#[test] |
| 213 | +fn perp_withdraw_prints_the_note_the_payout_will_be() { |
| 214 | + let dir = tempfile::tempdir().unwrap(); |
| 215 | + let key = keygen(&dir); |
| 216 | + let addr = address_of(&key); |
| 217 | + let trade = dir.path().join("t.json"); |
| 218 | + assert!(rand(DEAD, &key, &["perp", "keygen", "--out", trade.to_str().unwrap()]).ok); |
| 219 | + let node = trading_node(Some(0)); |
| 220 | + let r = rand(&node.url, &key, &["perp", "withdraw", "--trading-key", trade.to_str().unwrap(), "--amount", "123", "--no-wait"]); |
| 221 | + assert!(r.ok, "{}", r.err); |
| 222 | + assert!(r.out.contains(&format!("request {}", "ab".repeat(32))), "{}", r.out); |
| 223 | + assert!(r.out.contains(&format!("amount 123 units of asset 0 to {addr}")), "{}", r.out); |
| 224 | + assert!(r.out.contains("time 40\nr "), "the note's time is the head height: {}", r.out); |
| 225 | + assert!(r.out.contains("paid as that note when a state proof covers the request"), "{}", r.out); |
| 226 | + match &sent(&node)[0].action { |
| 227 | + Action::PerpWithdraw { .. } => {} |
| 228 | + other => panic!("not a withdrawal: {other:?}"), |
| 229 | + } |
| 230 | +} |
| 231 | + |
| 232 | +#[test] |
| 233 | +fn perp_oracle_signs_sorted_prices_and_refuses_bad_lists() { |
| 234 | + let dir = tempfile::tempdir().unwrap(); |
| 235 | + let key = keygen(&dir); |
| 236 | + let node_key = dir.path().join("node.json"); |
| 237 | + assert!(rand(DEAD, &key, &["perp", "keygen", "--out", node_key.to_str().unwrap()]).ok); |
| 238 | + let nk = node_key.to_str().unwrap(); |
| 239 | + let node = trading_node(None); |
| 240 | + let r = rand(&node.url, &key, &["perp", "oracle", "--node-key", nk, "--price", "3=300, 1=100", "--no-wait"]); |
| 241 | + assert!(r.ok, "{}", r.err); |
| 242 | + assert!(r.out.starts_with(&format!("oracle {} nonce ", "ab".repeat(32))), "{}", r.out); |
| 243 | + match &sent(&node)[0].action { |
| 244 | + Action::PerpOracle { prices, .. } => { |
| 245 | + assert_eq!(prices.iter().map(|p| (p.market, p.price)).collect::<Vec<_>>(), vec![(1, 100), (3, 300)]); |
| 246 | + } |
| 247 | + other => panic!("not an oracle submission: {other:?}"), |
| 248 | + } |
| 249 | + for (price, want) in [ |
| 250 | + ("1", "expected <market>=<units>"), |
| 251 | + ("x=5", "market is not a number"), |
| 252 | + ("1=y", "price is not a number of units"), |
| 253 | + ("1=0", "a price of 0 reads as no price"), |
| 254 | + ("1=5,1=6", "a market is priced twice"), |
| 255 | + (",", "at least one <market>=<units>"), |
| 256 | + ] { |
| 257 | + let r = rand(&node.url, &key, &["perp", "oracle", "--node-key", nk, "--price", price, "--no-wait"]); |
| 258 | + assert!(!r.ok && r.err.contains(want), "{price}: {}", r.err); |
| 259 | + } |
| 260 | + assert_eq!(sent(&node).len(), 1, "only the good list was sent"); |
| 261 | +} |
| 262 | + |
| 263 | +#[test] |
| 264 | +fn a_refused_oracle_submission_is_an_error_without_every_and_logged_with_it() { |
| 265 | + let dir = tempfile::tempdir().unwrap(); |
| 266 | + let key = keygen(&dir); |
| 267 | + let node_key = dir.path().join("node.json"); |
| 268 | + assert!(rand(DEAD, &key, &["perp", "keygen", "--out", node_key.to_str().unwrap()]).ok); |
| 269 | + let node = fake(Box::new(|m, _| match m { |
| 270 | + "rand_chainId" => Ok(json!(14)), |
| 271 | + "rand_sendTransaction" => Err((-32000, "oracle window closed".into())), |
| 272 | + _ => Err((-32601, "method not found".into())), |
| 273 | + })); |
| 274 | + let r = rand(&node.url, &key, &["perp", "oracle", "--node-key", node_key.to_str().unwrap(), "--price", "1=5", "--no-wait"]); |
| 275 | + assert!(!r.ok && r.err.contains("oracle window closed"), "{}", r.err); |
| 276 | +} |
| 277 | + |
| 278 | +#[test] |
| 279 | +fn perp_prove_refuses_a_bad_fri_name_and_a_missing_job() { |
| 280 | + let dir = tempfile::tempdir().unwrap(); |
| 281 | + let key = dir.path().join("k.json"); |
| 282 | + let job = dir.path().join("job.json"); |
| 283 | + let image = dir.path().join("engine.bin"); |
| 284 | + let r = rand(DEAD, &key, &["perp", "prove", "--image", image.to_str().unwrap(), "--job", job.to_str().unwrap()]); |
| 285 | + assert!(!r.ok && r.err.contains("reading"), "{}", r.err); |
| 286 | + std::fs::write(&job, "{}").unwrap(); |
| 287 | + let r = rand(DEAD, &key, &["perp", "prove", "--image", image.to_str().unwrap(), "--job", job.to_str().unwrap()]); |
| 288 | + assert!(!r.ok && r.err.contains("is not a perp prove job"), "{}", r.err); |
| 289 | +} |
0 commit comments