Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: emily validate deposits #1197

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 12 commits
Commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ Name | Type | Description | Notes
**bitcoin_txid** | **String** | Bitcoin transaction id. |
**deposit_script** | **String** | Deposit script. |
**reclaim_script** | **String** | Reclaim script. |
**transaction_hex** | **String** | The raw transaction hex. |

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ pub struct CreateDepositRequestBody {
/// Reclaim script.
#[serde(rename = "reclaimScript")]
pub reclaim_script: String,
/// The raw transaction hex.
#[serde(rename = "transactionHex")]
pub transaction_hex: String,
}

impl CreateDepositRequestBody {
Expand All @@ -35,12 +38,14 @@ impl CreateDepositRequestBody {
bitcoin_txid: String,
deposit_script: String,
reclaim_script: String,
transaction_hex: String,
) -> CreateDepositRequestBody {
CreateDepositRequestBody {
bitcoin_tx_output_index,
bitcoin_txid,
deposit_script,
reclaim_script,
transaction_hex,
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ Name | Type | Description | Notes
**bitcoin_txid** | **String** | Bitcoin transaction id. |
**deposit_script** | **String** | Deposit script. |
**reclaim_script** | **String** | Reclaim script. |
**transaction_hex** | **String** | The raw transaction hex. |

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ pub struct CreateDepositRequestBody {
/// Reclaim script.
#[serde(rename = "reclaimScript")]
pub reclaim_script: String,
/// The raw transaction hex.
#[serde(rename = "transactionHex")]
pub transaction_hex: String,
}

impl CreateDepositRequestBody {
Expand All @@ -35,12 +38,14 @@ impl CreateDepositRequestBody {
bitcoin_txid: String,
deposit_script: String,
reclaim_script: String,
transaction_hex: String,
) -> CreateDepositRequestBody {
CreateDepositRequestBody {
bitcoin_tx_output_index,
bitcoin_txid,
deposit_script,
reclaim_script,
transaction_hex,
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ Name | Type | Description | Notes
**bitcoin_txid** | **String** | Bitcoin transaction id. |
**deposit_script** | **String** | Deposit script. |
**reclaim_script** | **String** | Reclaim script. |
**transaction_hex** | **String** | The raw transaction hex. |

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ pub struct CreateDepositRequestBody {
/// Reclaim script.
#[serde(rename = "reclaimScript")]
pub reclaim_script: String,
/// The raw transaction hex.
#[serde(rename = "transactionHex")]
pub transaction_hex: String,
}

impl CreateDepositRequestBody {
Expand All @@ -35,12 +38,14 @@ impl CreateDepositRequestBody {
bitcoin_txid: String,
deposit_script: String,
reclaim_script: String,
transaction_hex: String,
) -> CreateDepositRequestBody {
CreateDepositRequestBody {
bitcoin_tx_output_index,
bitcoin_txid,
deposit_script,
reclaim_script,
transaction_hex,
}
}
}
1 change: 1 addition & 0 deletions emily/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ environment: {
LIMIT_TABLE_NAME: limitTableName,
IS_LOCAL: "true" | "false",
TRUSTED_REORG_API_KEY: trustedReorgApiKey,
IS_MAINNET: "true" | "false",
},
```

Expand Down
15 changes: 8 additions & 7 deletions emily/cdk/lib/emily-stack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,11 +140,11 @@ export class EmilyStack extends cdk.Stack {
indexName: byStatusIndexName,
partitionKey: {
name: 'OpStatus',
type: dynamodb.AttributeType.STRING
type: dynamodb.AttributeType.STRING
},
sortKey: {
name: 'LastUpdateHeight',
type: dynamodb.AttributeType.NUMBER
type: dynamodb.AttributeType.NUMBER
},
projectionType: dynamodb.ProjectionType.INCLUDE,
nonKeyAttributes: [
Expand All @@ -163,11 +163,11 @@ export class EmilyStack extends cdk.Stack {
indexName: byRecipientIndexName,
partitionKey: {
name: 'Recipient',
type: dynamodb.AttributeType.STRING
type: dynamodb.AttributeType.STRING
},
sortKey: {
name: 'LastUpdateHeight',
type: dynamodb.AttributeType.NUMBER
type: dynamodb.AttributeType.NUMBER
},
projectionType: dynamodb.ProjectionType.INCLUDE,
nonKeyAttributes: [
Expand Down Expand Up @@ -220,11 +220,11 @@ export class EmilyStack extends cdk.Stack {
indexName: indexName,
partitionKey: {
name: 'OpStatus',
type: dynamodb.AttributeType.STRING
type: dynamodb.AttributeType.STRING
},
sortKey: {
name: 'LastUpdateHeight',
type: dynamodb.AttributeType.NUMBER
type: dynamodb.AttributeType.NUMBER
},
projectionType: dynamodb.ProjectionType.INCLUDE,
nonKeyAttributes: [
Expand Down Expand Up @@ -316,7 +316,7 @@ export class EmilyStack extends cdk.Stack {
chainstateTableName: string,
limitTableName: string,
removalPolicy: cdk.RemovalPolicy,
props: EmilyStackProps
props: EmilyStackProps,
): lambda.Function {

const operationLambdaId: string = "OperationLambda";
Expand All @@ -343,6 +343,7 @@ export class EmilyStack extends cdk.Stack {
// already expected to be present in the lambda.
IS_LOCAL: "false",
TRUSTED_REORG_API_KEY: props.trustedReorgApiKey,
IS_MAINNET: props.stageName == Constants.PROD_STAGE_NAME ? "true" : "false",
},
description: `Emily Api Handler. ${EmilyStackUtils.getLambdaGitIdentifier()}`,
currentVersionOptions: {
Expand Down
3 changes: 2 additions & 1 deletion emily/cdk/test/emily-stack.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ describe('EmilyStack Test', () => {
// TODO(TBD): Add check for properties linking resources created during cdk build.
Handler: "main",
Runtime: "provided.al2023",
Architectures: [ "x86_64" ],
Architectures: ["x86_64"],
Timeout: 5,
});

Expand All @@ -64,6 +64,7 @@ describe('EmilyStack Test', () => {
expect(environment.LIMIT_TABLE_NAME).toMatch(`LimitTable-account-region-${Constants.UNIT_TEST_STAGE_NAME}`);
expect(environment.TRUSTED_REORG_API_KEY).toEqual("testApiKey");
expect(environment.IS_LOCAL).toEqual("false");
expect(environment.IS_MAINNET).toEqual("false");
});
});

Expand Down
86 changes: 12 additions & 74 deletions emily/handler/src/api/handlers/deposit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ use crate::api::models::deposit::responses::{
GetDepositsForTransactionResponse, UpdateDepositsResponse,
};
use crate::database::entries::StatusEntry;
use stacks_common::codec::StacksMessageCodec as _;
use tracing::{debug, instrument};
use warp::reply::{json, with_status, Reply};

Expand All @@ -24,7 +23,7 @@ use crate::database::entries::deposit::{
DepositEntry, DepositEntryKey, DepositEvent, DepositParametersEntry,
ValidatedUpdateDepositsRequest,
};
use bitcoin::ScriptBuf;
use stacks_common::codec::StacksMessageCodec as _;
use warp::http::StatusCode;

/// Get deposit handler.
Expand Down Expand Up @@ -260,7 +259,10 @@ pub async fn create_deposit(
context: EmilyContext,
body: CreateDepositRequestBody,
) -> impl warp::reply::Reply {
debug!("In create deposit");
debug!(
"Creating deposit with txid: {}, output index: {}",
body.bitcoin_txid, body.bitcoin_tx_output_index
);
// Internal handler so `?` can be used correctly while still returning a reply.
async fn handler(
context: EmilyContext,
Expand Down Expand Up @@ -298,33 +300,30 @@ pub async fn create_deposit(
Err(e) => return Err(e),
}

let status = Status::Pending;

// Get parameters from scripts.
let script_parameters =
scripts_to_resource_parameters(&body.deposit_script, &body.reclaim_script)?;
let limits = accessors::get_limits(&context).await?;
let deposit_info = body.validate(&limits, context.settings.is_mainnet)?;

// Make table entry.
let deposit_entry: DepositEntry = DepositEntry {
key: DepositEntryKey {
bitcoin_txid: body.bitcoin_txid,
bitcoin_tx_output_index: body.bitcoin_tx_output_index,
},
recipient: script_parameters.recipient,
recipient: hex::encode(deposit_info.recipient.serialize_to_vec()),
parameters: DepositParametersEntry {
max_fee: script_parameters.max_fee,
lock_time: script_parameters.lock_time,
max_fee: deposit_info.max_fee,
lock_time: deposit_info.lock_time.to_consensus_u32(),
},
history: vec![DepositEvent {
status: StatusEntry::Pending,
message: "Just received deposit".to_string(),
stacks_block_hash: stacks_block_hash.clone(),
stacks_block_height,
}],
status,
status: Status::Pending,
last_update_block_hash: stacks_block_hash,
last_update_height: stacks_block_height,
amount: script_parameters.amount,
amount: deposit_info.amount,
reclaim_script: body.reclaim_script,
deposit_script: body.deposit_script,
..Default::default()
Expand All @@ -343,40 +342,6 @@ pub async fn create_deposit(
.map_or_else(Reply::into_response, Reply::into_response)
}

/// Parameters from the deposit and reclaim scripts.
struct ScriptParameters {
amount: u64,
max_fee: u64,
recipient: String,
lock_time: u32,
}

/// Convert scripts to resource parameters.
///
/// This function is used to convert the deposit and reclaim scripts into the
/// parameters that are stored in the database.
fn scripts_to_resource_parameters(
deposit_script: &str,
reclaim_script: &str,
) -> Result<ScriptParameters, Error> {
let deposit_script_buf = ScriptBuf::from_hex(deposit_script)?;
let deposit_script_inputs = sbtc::deposits::DepositScriptInputs::parse(&deposit_script_buf)?;

let reclaim_script_buf = ScriptBuf::from_hex(reclaim_script)?;
let reclaim_script_inputs = sbtc::deposits::ReclaimScriptInputs::parse(&reclaim_script_buf)?;

let recipient_bytes = deposit_script_inputs.recipient.serialize_to_vec();
let recipient_hex_string = hex::encode(&recipient_bytes);

Ok(ScriptParameters {
// TODO(TBD): Get the amount from some script related data somehow.
amount: 0,
max_fee: deposit_script_inputs.max_fee,
recipient: recipient_hex_string,
lock_time: reclaim_script_inputs.lock_time(),
})
}

/// Update deposits handler.
#[utoipa::path(
put,
Expand Down Expand Up @@ -457,30 +422,3 @@ pub async fn update_deposits(
}

// TODO(393): Add handler unit tests.

// Test module
#[cfg(test)]
mod tests {

use super::*;
use sbtc::testing::{self, deposits::TxSetup};
use test_case::test_case;

#[test_case(15000, 500_000, 150; "All parameters are normal numbers")]
#[test_case(0, 0, 0; "All parameters are zeros")]
fn test_scripts_to_resource_parameters(max_fee: u64, amount_sats: u64, lock_time: u32) {
let setup: TxSetup = testing::deposits::tx_setup(lock_time, max_fee, amount_sats);

let deposit_script = setup.deposit.deposit_script().to_hex_string();
let reclaim_script = setup.reclaim.reclaim_script().to_hex_string();

let script_parameters: ScriptParameters =
scripts_to_resource_parameters(&deposit_script, &reclaim_script).unwrap();

assert_eq!(script_parameters.max_fee, max_fee);
assert_eq!(script_parameters.lock_time, lock_time);

// TODO: Test the recipient with an input value.
assert!(script_parameters.recipient.len() > 0);
}
}
Loading