Skip to content

Commit 8b0df15

Browse files
authored
*: fix claim tx (#83)
* spaces-cli: fix naming * mempool: move channel into inner and fix threaded test * vm: better handle errs with app_gossip * spacesvm: bump deps * name change cleanup * spaces-cli: add ping command and cleanup * spaces-cli: simplify output of successful tx Signed-off-by: Sam Batschelet <[email protected]>
1 parent 4a1bdbf commit 8b0df15

File tree

11 files changed

+150
-123
lines changed

11 files changed

+150
-123
lines changed

spaces-cli/Cargo.toml

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11
[package]
2-
name = "spacesvm_cli"
2+
name = "spaces-cli"
33
version = "0.0.0"
44
edition = "2021"
55
rust-version = "1.65"
66
publish = false
7-
description = "spacesvm_cli_for_issuing_RPC_commands"
7+
description = "spacesvm cli for issuing RPC commands"
88
license = "BSD-3-Clause"
99
homepage = "https://avax.network"
1010

1111
[dependencies]
12-
avalanche-types = { version = "0.0.135", features = ["subnet"] }
12+
avalanche-types = { version = "0.0.138", features = ["subnet"] }
1313
clap = { version = "4.0", features = ["derive"] }
1414
hex = "0.4.3"
1515
jsonrpc-core = "18.0.0"

spaces-cli/src/main.rs

+54-23
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,19 @@
1-
use std::error;
2-
use std::fs::File;
3-
use std::io::{Result, Write};
4-
use std::path::Path;
1+
use std::{
2+
error,
3+
fs::File,
4+
io::{Result, Write},
5+
path::Path,
6+
};
57

68
use avalanche_types::key;
79
use clap::{Parser, Subcommand};
810
use jsonrpc_client_transports::{transports, RpcError};
911
use jsonrpc_core::futures;
1012
use spacesvm::{
11-
api::{DecodeTxArgs, IssueTxArgs, ResolveArgs, ServiceClient as Client},
13+
api::{
14+
DecodeTxArgs, IssueTxArgs, IssueTxResponse, PingResponse, ResolveArgs, ResolveResponse,
15+
ServiceClient as Client,
16+
},
1217
chain::tx::{decoder, tx::TransactionType, unsigned::TransactionData},
1318
};
1419

@@ -46,6 +51,7 @@ enum Command {
4651
space: String,
4752
key: String,
4853
},
54+
Ping {},
4955
}
5056

5157
#[tokio::main]
@@ -55,22 +61,36 @@ async fn main() -> std::result::Result<(), Box<dyn error::Error>> {
5561
let secret_key = get_or_create_pk(&cli.private_key_file)?;
5662
let connection = transports::http::connect::<Client>(&cli.endpoint);
5763
let client = futures::executor::block_on(connection)?;
58-
ping(&client).await?;
5964

65+
// prints the value returned if available.
6066
if let Command::Get { space, key } = &cli.command {
61-
futures::executor::block_on(client.resolve(ResolveArgs {
62-
space: space.as_bytes().to_vec(),
63-
key: key.as_bytes().to_vec(),
64-
}))
65-
.map_err(|e| e.to_string())?;
67+
let resp =
68+
futures::executor::block_on(get(&client, space, key)).map_err(|e| e.to_string())?;
69+
log::debug!("{:?}", resp);
70+
71+
println!("{}", String::from_utf8_lossy(&resp.value));
72+
return Ok(());
73+
}
74+
75+
// returns on success and errors on failure
76+
if let Command::Ping {} = &cli.command {
77+
let resp = futures::executor::block_on(ping(&client)).map_err(|e| e.to_string())?;
78+
log::debug!("{:?}", resp);
79+
80+
return Ok(());
6681
}
6782

6883
let tx = command_to_tx(cli.command)?;
6984

70-
futures::executor::block_on(sign_and_submit(&client, &secret_key, tx))
71-
.map_err(|e| e.to_string().into())
85+
// prints the id of a successful transaction.
86+
let resp = futures::executor::block_on(sign_and_submit(&client, &secret_key, tx))
87+
.map_err(|e| e.to_string())?;
88+
println!("{}", resp.tx_id);
89+
90+
Ok(())
7291
}
7392

93+
/// Takes a TX command and returns transaction data.
7494
fn command_to_tx(command: Command) -> Result<TransactionData> {
7595
match command {
7696
Command::Claim { space } => Ok(claim_tx(space)),
@@ -83,6 +103,7 @@ fn command_to_tx(command: Command) -> Result<TransactionData> {
83103
}
84104
}
85105

106+
/// Returns a private key from a given path or creates new.
86107
fn get_or_create_pk(path: &str) -> Result<key::secp256k1::private_key::Key> {
87108
if !Path::new(path).try_exists()? {
88109
let secret_key = key::secp256k1::private_key::Key::generate().unwrap();
@@ -125,20 +146,18 @@ fn delete_tx(space: String, key: String) -> TransactionData {
125146
}
126147
}
127148

128-
async fn ping(client: &Client) -> Result<()> {
149+
async fn ping(client: &Client) -> Result<PingResponse> {
129150
let error_handling =
130151
|e: RpcError| std::io::Error::new(std::io::ErrorKind::Other, e.to_string());
131-
let resp = client.ping().await.map_err(error_handling);
132-
dbg!(resp.is_ok());
133-
dbg!(&resp);
134-
Ok(())
152+
client.ping().await.map_err(error_handling)
135153
}
136154

155+
/// Decodes transaction signs the typed data ans issues tx returning IssueTxResponse.
137156
async fn sign_and_submit(
138157
client: &Client,
139158
pk: &key::secp256k1::private_key::Key,
140159
tx_data: TransactionData,
141-
) -> Result<()> {
160+
) -> Result<IssueTxResponse> {
142161
let error_handling =
143162
|e: RpcError| std::io::Error::new(std::io::ErrorKind::Other, dbg!(e).to_string());
144163
let resp = client
@@ -151,13 +170,25 @@ async fn sign_and_submit(
151170
let dh = decoder::hash_structured_data(typed_data)?;
152171
let sig = pk.sign_digest(&dh.as_bytes())?;
153172

154-
let resp = client
173+
client
155174
.issue_tx(IssueTxArgs {
156175
typed_data: resp.typed_data,
157176
signature: sig.to_bytes().to_vec(),
158177
})
159178
.await
160-
.map_err(error_handling)?;
161-
println!("response: {:?}", resp);
162-
Ok(())
179+
.map_err(error_handling)
180+
}
181+
182+
/// Get returns a ResolveResponse.
183+
async fn get(client: &Client, space: &str, key: &str) -> Result<ResolveResponse> {
184+
let error_handling =
185+
|e: RpcError| std::io::Error::new(std::io::ErrorKind::Other, dbg!(e).to_string());
186+
187+
client
188+
.resolve(ResolveArgs {
189+
space: space.as_bytes().to_vec(),
190+
key: key.as_bytes().to_vec(),
191+
})
192+
.await
193+
.map_err(error_handling)
163194
}

spacesvm/Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ name = "spacesvm"
1515
path = "src/bin/spaces/main.rs"
1616

1717
[dependencies]
18-
avalanche-types = { version = "0.0.135", features = ["subnet"] }
18+
avalanche-types = { version = "0.0.138", features = ["subnet"] }
1919
byteorder = "1.4.3"
2020
chrono = "0.4.22"
2121
crossbeam-channel = "0.5.6"

spacesvm/src/bin/spaces/main.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use log::info;
66

77
use spacesvm::{genesis, vm};
88

9-
pub const APP_NAME: &str = "spaces-vm-rs";
9+
pub const APP_NAME: &str = "spacesvm-rs";
1010

1111
#[tokio::main]
1212
async fn main() -> Result<()> {

spacesvm/src/chain/storage.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -239,18 +239,18 @@ pub async fn has_space(
239239
db.has(&space_info_key(space)).await
240240
}
241241

242-
/// 'KEY_PREFIX' + 'BYTE_DELIMITER' + [r_bucket] + 'BYTE_DELIMITER' + [key]
243-
pub fn space_value_key(r_bucket: ids::short::Id, key: &[u8]) -> Vec<u8> {
242+
/// 'KEY_PREFIX' + 'BYTE_DELIMITER' + [r_space] + 'BYTE_DELIMITER' + [key]
243+
pub fn space_value_key(r_space: ids::short::Id, key: &[u8]) -> Vec<u8> {
244244
let mut k: Vec<u8> = Vec::with_capacity(2 + SHORT_ID_LEN + 1 + key.len());
245245
k.push(KEY_PREFIX);
246246
k.push(BYTE_DELIMITER);
247-
k.extend_from_slice(r_bucket.as_ref());
247+
k.extend_from_slice(r_space.as_ref());
248248
k.push(BYTE_DELIMITER);
249249
k.extend_from_slice(key);
250250
k
251251
}
252252

253-
/// 'INFO_PREFIX' + 'BYTE_DELIMITER' + [bucket]
253+
/// 'INFO_PREFIX' + 'BYTE_DELIMITER' + [space]
254254
pub fn space_info_key(space: &[u8]) -> Vec<u8> {
255255
let mut k: Vec<u8> = Vec::with_capacity(space.len() + 2);
256256
k.push(INFO_PREFIX);

spacesvm/src/chain/tx/decoder.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ pub const TD_STRING: &str = "string";
1515
pub const TD_U64: &str = "u64";
1616
pub const TD_BYTES: &str = "bytes";
1717
pub const TD_BLOCK_ID: &str = "blockId";
18-
pub const TD_SPACE: &str = "bucket";
18+
pub const TD_SPACE: &str = "space";
1919
pub const TD_KEY: &str = "key";
2020
pub const TD_VALUE: &str = "value";
2121

spacesvm/src/chain/tx/delete.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ use super::{
1717
unsigned,
1818
};
1919

20-
/// Removes a key and value from the underlying bucket. No error will return
20+
/// Removes a key and value from the underlying space. No error will return
2121
/// if the key is not found.
2222
#[derive(Serialize, Deserialize, Clone, Debug, Default)]
2323
#[serde(rename_all = "camelCase")]
@@ -63,14 +63,14 @@ impl unsigned::Transaction for Tx {
6363
if info.is_none() {
6464
return Err(Error::new(
6565
ErrorKind::NotFound,
66-
format!("bucket not found: {}", self.space),
66+
format!("space not found: {}", self.space),
6767
));
6868
}
6969
let info = info.unwrap();
7070
if info.owner != txn_ctx.sender {
7171
return Err(Error::new(
7272
ErrorKind::PermissionDenied,
73-
format!("sets only allowed for bucket owner: {}", self.space),
73+
format!("sets only allowed for space owner: {}", self.space),
7474
));
7575
}
7676

spacesvm/src/chain/tx/set.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,8 @@ use super::{
2222
const HASH_LEN: usize = 66;
2323

2424
/// Performs a write against the logical keyspace. If the key exists
25-
/// the value will be overwritten. The root bucket must be created
26-
/// in advance.
25+
/// the value will be overwritten. The space must be created in
26+
/// advance.
2727
#[derive(Serialize, Deserialize, Clone, Debug)]
2828

2929
pub struct Tx {

spacesvm/src/chain/tx/tx.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ use super::{decoder, unsigned::TransactionContext};
1616
pub enum TransactionType {
1717
/// Root namespace.
1818
Claim,
19-
/// Create or update a key/value pair for a bucket.
19+
/// Create or update a key/value pair for a space.
2020
Set,
2121
/// Remove a key.
2222
Delete,
@@ -33,7 +33,7 @@ impl Default for TransactionType {
3333
impl fmt::Display for TransactionType {
3434
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3535
match self {
36-
TransactionType::Claim => write!(f, "bucket"),
36+
TransactionType::Claim => write!(f, "claim"),
3737
TransactionType::Set => write!(f, "set"),
3838
TransactionType::Delete => write!(f, "delete"),
3939
TransactionType::Unknown => write!(f, "unknown"),

0 commit comments

Comments
 (0)