Skip to content

Commit

Permalink
little backend fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
jazzandrock committed Sep 5, 2019
1 parent 358f51a commit 458ac94
Show file tree
Hide file tree
Showing 9 changed files with 126 additions and 19 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

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

4 changes: 2 additions & 2 deletions contracts/contracts/Franklin.sol
Original file line number Diff line number Diff line change
Expand Up @@ -456,7 +456,7 @@ contract Franklin {

uint16 tokenId = uint16(
(uint256(uint8(_publicData[opDataPointer + 3])) << 8) +
uint256(uint8(_publicData[opDataPointer + 4]))
(uint256(uint8(_publicData[opDataPointer + 4])) << 0)
);

uint8[3] memory amountPacked;
Expand Down Expand Up @@ -491,7 +491,7 @@ contract Franklin {
account,
(amount + fee)
);
return (5 * 8, 1);
return (4 * 8, 1);
}

// partial_exit
Expand Down
20 changes: 10 additions & 10 deletions core/models/src/node/operations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ pub struct DepositOp {
}

impl DepositOp {
const CHUNKS: usize = 4;
const OP_CODE: u8 = 0x01;
pub const CHUNKS: usize = 4;
pub const OP_CODE: u8 = 0x01;

fn get_public_data(&self) -> Vec<u8> {
let mut data = Vec::new();
Expand All @@ -33,8 +33,8 @@ pub struct TransferToNewOp {
}

impl TransferToNewOp {
const CHUNKS: usize = 5;
const OP_CODE: u8 = 0x02;
pub const CHUNKS: usize = 5;
pub const OP_CODE: u8 = 0x02;

fn get_public_data(&self) -> Vec<u8> {
let mut data = Vec::new();
Expand All @@ -58,8 +58,8 @@ pub struct TransferOp {
}

impl TransferOp {
const CHUNKS: usize = 2;
const OP_CODE: u8 = 0x05;
pub const CHUNKS: usize = 2;
pub const OP_CODE: u8 = 0x05;

fn get_public_data(&self) -> Vec<u8> {
let mut data = Vec::new();
Expand All @@ -81,8 +81,8 @@ pub struct PartialExitOp {
}

impl PartialExitOp {
const CHUNKS: usize = 4;
const OP_CODE: u8 = 0x03;
pub const CHUNKS: usize = 4;
pub const OP_CODE: u8 = 0x03;

fn get_public_data(&self) -> Vec<u8> {
let mut data = Vec::new();
Expand All @@ -104,8 +104,8 @@ pub struct CloseOp {
}

impl CloseOp {
const CHUNKS: usize = 1;
const OP_CODE: u8 = 0x04;
pub const CHUNKS: usize = 1;
pub const OP_CODE: u8 = 0x04;

fn get_public_data(&self) -> Vec<u8> {
let mut data = Vec::new();
Expand Down
13 changes: 13 additions & 0 deletions core/plasma/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,19 @@ impl PlasmaState {
self.balance_tree.items.get(&account_id).cloned()
}

pub fn chunks_for_tx(&self, franklin_tx: &FranklinTx) -> usize {
match franklin_tx {
FranklinTx::Transfer(tx) => if self.get_account_by_address(&tx.to).is_some() {
TransferOp::CHUNKS
} else {
TransferToNewOp::CHUNKS
},
FranklinTx::Deposit(_) => DepositOp::CHUNKS,
FranklinTx::Withdraw(_) => PartialExitOp::CHUNKS,
FranklinTx::Close(_) => CloseOp::CHUNKS,
}
}

pub fn apply_tx(&mut self, tx: FranklinTx) -> Result<TxSuccess, Error> {
match tx {
FranklinTx::Transfer(tx) => self.apply_transfer(tx),
Expand Down
29 changes: 29 additions & 0 deletions core/server/src/api_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,32 @@ fn handle_get_testnet_config(req: &HttpRequest<AppState>) -> ActixResult<HttpRes
// Ok(HttpResponse::Ok().json(tx))
//}

fn handle_get_executed_transaction_by_hash(req: &HttpRequest<AppState>) -> ActixResult<HttpResponse> {
let pool = req.state().connection_pool.clone();

let storage = pool.access_storage();
if storage.is_err() {
return Ok(HttpResponse::Ok().json(ApiError {
error: "rate limit".to_string(),
}));
}
let storage = storage.unwrap();

let transaction_hash_string = req.match_info().get("tx_hash");
if transaction_hash_string.is_none() {
return Ok(HttpResponse::Ok().json(ApiError {
error: "invalid parameters".to_string(),
}));
}
let transaction_hash_string = transaction_hash_string.unwrap();

let tx = storage.is_tx_successful(transaction_hash_string);
let tx = tx.unwrap();

Ok(HttpResponse::Ok().json(tx))
}


fn handle_get_network_status(req: &HttpRequest<AppState>) -> ActixResult<HttpResponse> {
let network_status = req.state().network_status.read();
Ok(HttpResponse::Ok().json(network_status))
Expand Down Expand Up @@ -520,6 +546,9 @@ fn start_server(state: AppState, bind_to: String) {
// .resource("/blocks/transactions/{tx_id}", |r| {
// r.method(Method::GET).f(handle_get_transaction_by_id);
// })
.resource("/transactions/{tx_hash}", |r| {
r.method(Method::GET).f(handle_get_executed_transaction_by_hash);
})
.resource("/blocks/{block_id}/transactions", |r| {
r.method(Method::GET).f(handle_get_block_transactions);
})
Expand Down
12 changes: 7 additions & 5 deletions core/server/src/state_keeper/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ impl PlasmaStateKeeper {
filtered_txs
.into_iter()
.take_while(|tx| {
total_chunks += tx.min_number_of_chunks();
total_chunks += self.state.chunks_for_tx(&tx);
total_chunks <= BLOCK_SIZE_CHUNKS
})
.collect()
Expand All @@ -239,7 +239,7 @@ impl PlasmaStateKeeper {
{
ensure!(
locked_balance.amount >= &deposit.amount + &deposit.fee,
"Locked amount insufficient"
"Locked amount insufficient, locked: {}, deposit: {}", locked_balance.amount, deposit.amount
);
ensure!(
locked_balance.blocks_left_until_unlock > 10,
Expand All @@ -258,10 +258,11 @@ impl PlasmaStateKeeper {
let mut accounts_updated = Vec::new();
let mut fees = Vec::new();
let mut ops = Vec::new();
let mut chunks_used = 0;
let mut chunks_left = BLOCK_SIZE_CHUNKS;

for tx in transactions.into_iter() {
if chunks_used >= BLOCK_SIZE_CHUNKS {
let chunks_needed = self.state.chunks_for_tx(&tx);
if chunks_left < chunks_needed {
break;
}

Expand All @@ -285,7 +286,8 @@ impl PlasmaStateKeeper {
mut updates,
executed_op,
}) => {
chunks_used += executed_op.chunks();
assert!(chunks_needed == executed_op.chunks());
chunks_left -= chunks_needed;
accounts_updated.append(&mut updates);
fees.push(fee);
let exec_result = ExecutedTx {
Expand Down
1 change: 1 addition & 0 deletions core/storage/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ ff = { package = "ff_ce", version = "0.6.0", features = ["derive"] }
chrono = { version = "0.4", features = ["serde", "rustc-serialize"] }
log = "0.4"
failure = "0.1"
hex = "0.3"

[dev-dependencies]
env_logger = "0.6"
58 changes: 57 additions & 1 deletion core/storage/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ extern crate diesel;
#[macro_use]
extern crate log;

use bigdecimal::BigDecimal;
use bigdecimal::{BigDecimal, Zero};
use chrono::prelude::*;
use diesel::dsl::*;
use failure::Fail;
Expand All @@ -30,6 +30,8 @@ use diesel::r2d2::{ConnectionManager, Pool, PoolError, PooledConnection};
use serde_json::value::Value;
use std::env;

use hex;

use diesel::sql_types::{BigInt, Nullable, Text, Timestamp};
sql_function!(coalesce, Coalesce, (x: Nullable<BigInt>, y: BigInt) -> BigInt);

Expand Down Expand Up @@ -149,6 +151,15 @@ struct StoredExecutedTransaction {
fail_reason: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct TxReceiptResponse {
tx_hash: Vec<u8>,
block_number: Option<i64>,
success: bool,
verified: bool,
fail_reason: Option<String>,
}

impl NewExecutedTransaction {
fn prepare_stored_tx(exec_tx: &ExecutedTx, block: BlockNumber) -> Self {
Self {
Expand Down Expand Up @@ -541,6 +552,8 @@ pub enum TxAddError {
NonceTooLow,
#[fail(display = "Tx signature is incorrect.")]
InvalidSignature,
#[fail(display = "Tx amount is zero.")]
ZeroAmount
}

enum ConnectionHolder {
Expand Down Expand Up @@ -1186,6 +1199,43 @@ impl StorageProcessor {
Ok((Some(account_id), verified_state, commited_state))
}

pub fn is_tx_successful(&self, hash: &str) -> QueryResult<(Option<TxReceiptResponse>)> {
self.conn().transaction(|| {
let hash = hex::decode(hash).unwrap();

let tx = executed_transactions::table
.filter(executed_transactions::tx_hash.eq(&hash))
.first::<StoredExecutedTransaction>(self.conn())
.optional()?;

if tx.is_some() {
let tx = tx.unwrap();

let confirm = operations::table
.filter(operations::block_number.eq(tx.block_number))
.filter(operations::action_type.eq("Verify"))
.first::<StoredOperation>(self.conn())
.optional()?;

Ok(Some(TxReceiptResponse {
tx_hash: hash,
block_number: Some(tx.block_number),
success: tx.success,
verified: confirm.is_some(),
fail_reason: tx.fail_reason
}))
} else {
Ok(Some(TxReceiptResponse {
tx_hash: hash,
block_number: None,
success: false,
verified: false,
fail_reason: Some("not committed yet".to_string())
}))
}
})
}

pub fn last_committed_state_for_account(
&self,
account_id: AccountId,
Expand Down Expand Up @@ -1520,6 +1570,12 @@ impl StorageProcessor {
return Ok(Err(TxAddError::NonceTooLow));
}

if let FranklinTx::Deposit(deposit_tx) = tx {
if deposit_tx.amount == bigdecimal::BigDecimal::zero() {
return Ok(Err(TxAddError::ZeroAmount));
}
}

let tx_failed = executed_transactions::table
.filter(executed_transactions::tx_hash.eq(tx.hash()))
.filter(executed_transactions::success.eq(false))
Expand Down
7 changes: 6 additions & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -75,4 +75,9 @@ services:
- type: bind
source: ./volumes/tesseracts
target: /var/lib/tesseracts/data

metabase:
image: metabase/metabase
ports:
- 2112:3000
volumes:
- ./metabase-data:/metabase-data

0 comments on commit 458ac94

Please sign in to comment.