Skip to content
This repository was archived by the owner on Jun 6, 2024. It is now read-only.
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
51 commits
Select commit Hold shift + click to select a range
7c1c88c
added inititial structure for api server and /wallet routes, requests…
p0lunin Nov 30, 2020
9dce723
splited /api folder at /api/network and /api/wallet folders
p0lunin Nov 30, 2020
9cd6938
added network responses
p0lunin Nov 30, 2020
942e88f
moved RawTx from responses to requests
p0lunin Nov 30, 2020
7a2d6fa
added /network routes, responses and requests. moved Cursor to data.rs
p0lunin Nov 30, 2020
40b4535
make fields in responses and requests public
p0lunin Dec 1, 2020
64e8f9c
make xpub Vec<u8> instead of [u8; 64]
p0lunin Dec 1, 2020
46b1e3f
added /wallet/new handling
p0lunin Dec 1, 2020
d8886af
removed id from /wallet handlers
p0lunin Dec 1, 2020
902fa5b
added WalletRef as arg for handlers in /wallet
p0lunin Dec 1, 2020
f8b4022
fixed ok: false in err() methods
p0lunin Dec 1, 2020
ac2cbe1
Revert "fixed ok: false in err() methods"
p0lunin Dec 1, 2020
8bdde5c
fixed ok: false in err() methods
p0lunin Dec 1, 2020
8c83f36
added /wallet/balance handling
p0lunin Dec 1, 2020
468a4fa
added cursor fields
p0lunin Dec 1, 2020
2e0ffd8
make fields pub, added const var for Cursor
p0lunin Dec 1, 2020
9cf1ab9
changed wallet_ref.write() to read()
p0lunin Dec 1, 2020
247f9b3
removed wallet_id from /wallet routes
p0lunin Dec 1, 2020
0cae807
added handling /wallet/address
p0lunin Dec 1, 2020
28449fe
added handling /wallet/receiver
p0lunin Dec 1, 2020
cf29045
added some data types
p0lunin Dec 2, 2020
940b14b
make struct public
p0lunin Dec 2, 2020
9151a03
make fields public
p0lunin Dec 2, 2020
cae3053
added read_xprv method
p0lunin Dec 2, 2020
de8ec05
added posibility to add TxAction in TxBuilder by hand
p0lunin Dec 2, 2020
737d20c
changed BuiltTx fields to one field with Tx
p0lunin Dec 2, 2020
25c80e8
changed Tx type
p0lunin Dec 2, 2020
7202d24
added /wallet/buildtx handling
p0lunin Dec 2, 2020
4d918b7
moved creating tx_action to function build_tx_action_to_tx_action
p0lunin Dec 2, 2020
4ae2e19
fmt
p0lunin Dec 2, 2020
c590bd5
added futures_util
p0lunin Dec 3, 2020
5abaf8d
improved handlers api: now it returns ResponseResult<T>
p0lunin Dec 3, 2020
9517b0a
moved combinators to warp_utils
p0lunin Dec 3, 2020
4e0dc61
added imports from warp_utils
p0lunin Dec 3, 2020
6df8db1
added BlockchainRef as arg to routes
p0lunin Dec 3, 2020
6a24e7c
changed return type of handlers to ResponseResult
p0lunin Dec 3, 2020
0bdd828
added blank implementations for /network/status and /network/mempool
p0lunin Dec 3, 2020
9a88ca4
change holes to concrete values
p0lunin Dec 3, 2020
decc582
added stub implementation for /network/blocks and /network/block
p0lunin Dec 4, 2020
4a3ce11
changed cursor api
p0lunin Dec 4, 2020
51e9b3e
renamed dto struct to *DTO
p0lunin Dec 4, 2020
fdca26c
precompute Tx in /wallet/buildtx to compute FeeRate
p0lunin Dec 4, 2020
2766603
blanked implementation for /network/tx
p0lunin Dec 4, 2020
46a7d32
added tests for /wallet/new route
p0lunin Dec 4, 2020
87c445d
removed DTO prefix, rename api::dto module to api::types
p0lunin Dec 8, 2020
1631977
removed :id parameter in the table of contents
p0lunin Dec 8, 2020
b995b69
fixed typo
p0lunin Dec 8, 2020
18bce49
added implementation TryFrom<BlockTx> for api::types::Tx
p0lunin Dec 8, 2020
f8c874d
fmt + prettifying
p0lunin Dec 8, 2020
d5959b4
fixed links in the table of contents
p0lunin Dec 8, 2020
e498280
routes are made as local vars
p0lunin Dec 8, 2020
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions node/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ time = "^0.1"
serde = { version = "1.0", features=["derive"] }
hex = "^0.3"
futures = "0.3"
futures-util = "0.3"
tokio = {version = "0.2", features=["full"]}
warp = "0.2"
tera = "1"
Expand Down
40 changes: 16 additions & 24 deletions node/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,11 @@
* [/network/tx/:id](#networktxid)
* [Wallet API](#wallet-api)
* [/wallet/new](#walletnew)
* [/wallet/:id/balance](#walletidbalance)
* [/wallet/:id/txs](#walletidtxs)
* [/wallet/:id/address](#walletidaddress)
* [/wallet/:id/receiver](#walletidreceiver)
* [/wallet/:id/buildtx](#walletidbuildtx)
* [/wallet/balance](#walletbalance)
* [/wallet/txs](#wallettxs)
* [/wallet/address](#walletaddress)
* [/wallet/receiver](#walletreceiver)
* [/wallet/buildtx](#walletbuildtx)


Responses are listed in JSON for a time being, but we are also going to provide the API responses via XDR format.
Expand Down Expand Up @@ -312,7 +312,7 @@ forming transactions and tracking the state of unspent outputs.

### /wallet/new

Creates a new wallet
Creates a new wallet. Successful submission returns 200 OK status.

Request:

Expand All @@ -325,21 +325,13 @@ struct NewWalletRequest {
}
```

Response:

```rust
struct NewWalletResponse {
id: [u8; 32],
}
```

### /wallet/:id/balance
### /wallet/balance

Returns wallet's balance.

Request:

`GET /wallet/:id/balance`
`GET /wallet/balance`

Response:

Expand All @@ -350,13 +342,13 @@ struct Balance {
```


### /wallet/:id/txs
### /wallet/txs

Lists annotated transactions.

Request:

`GET /wallet/:id/txs?cursor=[5786...]`
`GET /wallet/txs?cursor=[5786...]`

Response:

Expand All @@ -367,13 +359,13 @@ struct WalletTxs {
}
```

### /wallet/:id/address
### /wallet/address

Generates a new address.

Request:

`GET /wallet/:id/address`
`GET /wallet/address`

Response:

Expand All @@ -383,13 +375,13 @@ struct NewAddress {
}
```

### /wallet/:id/receiver
### /wallet/receiver

Generates a new receiver.

Request:

`POST /wallet/:id/receiver`
`POST /wallet/receiver`

```rust
struct NewReceiverRequest {
Expand All @@ -407,13 +399,13 @@ struct NewReceiverResponse {
}
```

### /wallet/:id/buildtx
### /wallet/buildtx

Builds a transaction and returns the signing instructions.

Request:

`POST /wallet/:id/buildtx`
`POST /wallet/buildtx`

```rust
struct BuildTxRequest {
Expand Down
27 changes: 21 additions & 6 deletions node/src/api.rs
Original file line number Diff line number Diff line change
@@ -1,24 +1,39 @@
mod network;
mod response;
pub(self) mod serde_utils;
mod types;
mod wallet;
mod warp_utils;

use std::net::SocketAddr;
use warp::Filter;

use crate::bc::BlockchainRef;
use crate::config::Config;
use crate::wallet_manager::WalletRef;
use std::convert::Infallible;

/// Launches the API server.
pub async fn launch(config: Config, bc: BlockchainRef, wallet: WalletRef) {
let conf = &config.data.api;
if conf.disabled {
return;
}
let echo =
warp::path!("v1" / "echo" / String).map(|thingy| format!("API v1 echo: {}!", thingy));
let routes = routes(bc, wallet);

eprintln!("API: http://{}", &conf.listen);
warp::serve(routes).run(conf.listen).await;
}

fn routes(
bc: BlockchainRef,
wallet: WalletRef,
) -> impl Filter<Extract = impl warp::Reply, Error = Infallible> + Clone {
let wallet_routes = wallet::routes(wallet);
let network_routes = network::routes(bc);

let not_found = warp::any()
.map(|| warp::reply::with_status("Not found.", warp::http::StatusCode::NOT_FOUND));

let routes = echo.or(not_found);

eprintln!("API: http://{}", &conf.listen);
warp::serve(routes).run(conf.listen).await;
wallet_routes.or(network_routes).or(not_found)
}
56 changes: 56 additions & 0 deletions node/src/api/network.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
mod handlers;
mod requests;
mod responses;

use crate::api::types::{Cursor, HexId};
use crate::api::warp_utils::{handle1, handle2};
use crate::bc::BlockchainRef;
use std::convert::Infallible;
use warp::Filter;

pub fn routes(
bc: BlockchainRef,
) -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
use warp::*;

let status = path!("v1" / "network" / "status")
.and(get())
.and(with_bc(bc.clone()))
.and_then(handle1(handlers::status));

let mempool = path!("v1" / "network" / "mempool")
.and(get())
.and(query::<Cursor>())
.and(with_bc(bc.clone()))
.and_then(handle2(handlers::mempool));

let blocks = path!("v1" / "network" / "blocks")
.and(get())
.and(query::<Cursor>())
.and(with_bc(bc.clone()))
.and_then(handle2(handlers::blocks));

let block = path!("v1" / "network" / "block" / HexId)
.and(get())
.and(with_bc(bc.clone()))
.and_then(handle2(handlers::block));

let tx = path!("v1" / "network" / "tx" / HexId)
.and(get())
.and(with_bc(bc.clone()))
.and_then(handle2(handlers::tx));

let submit = path!("v1" / "network" / "submit")
.and(post())
.and(body::json())
.and(with_bc(bc.clone()))
.and_then(handle2(handlers::submit));

status.or(mempool).or(blocks).or(block).or(tx).or(submit)
}

fn with_bc(
bc: BlockchainRef,
) -> impl Filter<Extract = (BlockchainRef,), Error = Infallible> + Clone {
warp::any().map(move || bc.clone())
}
141 changes: 141 additions & 0 deletions node/src/api/network/handlers.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
use crate::{
api::{
network::{requests, responses},
response::{error, ResponseResult},
types,
types::{Cursor, HexId},
},
bc::BlockchainRef,
};
use blockchain::{BlockHeader, BlockchainState, Mempool};
use std::convert::TryFrom;
use zkvm::Tx;

pub(super) async fn status(bc: BlockchainRef) -> ResponseResult<responses::Status> {
let bc_state = BlockchainState::make_initial(5, vec![]).0;
let mempool = &Mempool::new(bc_state.clone(), 5);

let status = mempool_status(mempool);
let state = &bc_state;
let tip = state.tip.clone().into();
let utreexo = [None; 64];

let state = types::State { tip, utreexo };

let peers = vec![];

Ok(responses::Status {
mempool: status,
state,
peers,
})
}

pub(super) async fn mempool(
cursor: types::Cursor,
bc: BlockchainRef,
) -> ResponseResult<responses::MempoolTxs> {
let bc_state = BlockchainState::make_initial(5, vec![]).0;
let mempool = &Mempool::new(bc_state.clone(), 5);
let txs_owned = Vec::<blockchain::BlockTx>::new();
let txs = txs_owned.iter();

let offset = cursor
.cursor
.parse::<usize>()
.map_err(|_| error::invalid_cursor())?;
let elements = cursor.count() as usize;

let status = mempool_status(mempool);
let txs = txs
.skip(offset)
.take(elements)
.map(|tx| types::Tx::try_from(tx.clone()))
.collect::<Result<Vec<_>, _>>()
.map_err(|_| error::tx_compute_error())?;

Ok(responses::MempoolTxs {
cursor: (offset + elements).to_string(),
status,
txs,
})
}

pub(super) async fn blocks(cursor: Cursor, bc: BlockchainRef) -> ResponseResult<responses::Blocks> {
let blocks_headers = Vec::<BlockHeader>::new();

let offset = cursor
.cursor
.parse::<usize>()
.map_err(|_| error::invalid_cursor())?;
let count = cursor.count() as usize;

let headers = blocks_headers
.iter()
.skip(offset)
.take(count)
.map(|b| b.clone().into())
.collect::<Vec<_>>();
Ok(responses::Blocks {
cursor: (offset + count).to_string(),
blocks: headers,
})
}

pub(super) async fn block(block_id: HexId, bc: BlockchainRef) -> ResponseResult<responses::Block> {
let header = BlockHeader::make_initial(0, zkvm::Hash::default());
let txs = Vec::<blockchain::BlockTx>::new();

Ok(responses::Block {
header: header.into(),
txs,
})
}

pub(super) async fn tx(tx_id: HexId, bc: BlockchainRef) -> ResponseResult<responses::TxResponse> {
let block_tx = blockchain::BlockTx {
tx: Tx {
header: zkvm::TxHeader {
version: 0,
mintime_ms: 0,
maxtime_ms: 0,
},
program: vec![],
signature: musig::Signature {
s: Default::default(),
R: Default::default(),
},
proof: zkvm::bulletproofs::r1cs::R1CSProof::from_bytes(&[0; 1 + 15 * 32]).unwrap(),
},
proofs: vec![],
};

let tx = types::Tx::try_from(block_tx).map_err(|_| error::tx_compute_error())?;

let status = responses::TxStatus {
confirmed: true,
block_height: 0,
block_id: [0; 32],
};

Ok(responses::TxResponse { status, tx })
}

pub(super) async fn submit(
raw_tx: requests::RawTx,
bc: BlockchainRef,
) -> ResponseResult<responses::Submit> {
unimplemented!()
}

fn mempool_status(mempool: &Mempool) -> types::MempoolStatus {
let count = mempool.entries().count() as u64;
let size = mempool.len() as u64;
let feerate = 0;

types::MempoolStatus {
count,
size,
feerate,
}
}
14 changes: 14 additions & 0 deletions node/src/api/network/requests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
use serde::Deserialize;

use crate::api::serde_utils::BigArray;
use crate::api::types::TxHeader;

#[derive(Deserialize)]
pub struct RawTx {
pub header: TxHeader,
pub program: Vec<u8>,
#[serde(with = "BigArray")]
pub signature: [u8; 64],
pub r1cs_proof: Vec<u8>,
pub utreexo_proofs: Vec<Vec<u8>>,
}
Loading