use crate::api::types::Token;
use crate::error::{Error, Result};
use crate::signer::PrivateKey;
use serde::{Deserialize, Serialize};
pub type TxId = String;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct OutputRef {
pub hint: i32,
#[serde(rename = "key")]
pub tx_hash: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AssetInput {
#[serde(rename = "outputRef")]
pub output_ref: OutputRef,
#[serde(rename = "unlockScript")]
pub unlock_script: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AssetOutput {
#[serde(rename = "address")]
pub address: String,
#[serde(rename = "attoAlphAmount")]
pub atto_alph_amount: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub tokens: Option<Vec<Token>>,
#[serde(rename = "lockTime", skip_serializing_if = "Option::is_none")]
pub lock_time: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
}
impl AssetOutput {
pub fn new(address: String, atto_alph_amount: String) -> Self {
Self {
address,
atto_alph_amount,
tokens: None,
lock_time: None,
message: None,
}
}
pub fn with_tokens(mut self, tokens: Vec<Token>) -> Self {
self.tokens = Some(tokens);
self
}
pub fn with_lock_time(mut self, lock_time: u64) -> Self {
self.lock_time = Some(lock_time);
self
}
pub fn with_message(mut self, message: String) -> Self {
self.message = Some(message);
self
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ContractOutput {
#[serde(rename = "address")]
pub address: String,
#[serde(rename = "attoAlphAmount")]
pub atto_alph_amount: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub tokens: Option<Vec<Token>>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum Output {
#[serde(rename = "AssetOutput")]
Asset(AssetOutput),
#[serde(rename = "ContractOutput")]
Contract(ContractOutput),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct UnsignedTransaction {
#[serde(rename = "txId")]
pub tx_id: TxId,
pub version: u8,
#[serde(rename = "networkId")]
pub network_id: u8,
#[serde(rename = "gasAmount")]
pub gas_amount: u32,
#[serde(rename = "gasPrice")]
pub gas_price: String,
pub inputs: Vec<AssetInput>,
#[serde(rename = "fixedOutputs")]
pub fixed_outputs: Vec<AssetOutput>,
#[serde(rename = "scriptOpt", skip_serializing_if = "Option::is_none")]
pub script_opt: Option<String>,
}
impl UnsignedTransaction {
pub fn id(&self) -> &str {
&self.tx_id
}
pub fn input_count(&self) -> usize {
self.inputs.len()
}
pub fn output_count(&self) -> usize {
self.fixed_outputs.len()
}
pub fn total_output_amount(&self) -> Result<u128> {
let mut total = 0u128;
for output in &self.fixed_outputs {
let amount: u128 = output
.atto_alph_amount
.parse()
.map_err(|e| Error::InvalidValue(format!("Invalid amount: {}", e)))?;
total = total
.checked_add(amount)
.ok_or_else(|| Error::InvalidValue("Amount overflow".to_string()))?;
}
Ok(total)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Transaction {
pub unsigned: UnsignedTransaction,
#[serde(rename = "scriptExecutionOk")]
pub script_execution_ok: bool,
#[serde(rename = "contractInputs")]
pub contract_inputs: Vec<OutputRef>,
#[serde(rename = "generatedOutputs")]
pub generated_outputs: Vec<Output>,
#[serde(rename = "inputSignatures")]
pub input_signatures: Vec<String>,
#[serde(rename = "scriptSignatures")]
pub script_signatures: Vec<String>,
}
impl Transaction {
pub fn id(&self) -> &str {
self.unsigned.id()
}
pub fn is_successful(&self) -> bool {
self.script_execution_ok
}
pub fn signature_count(&self) -> usize {
self.input_signatures.len() + self.script_signatures.len()
}
}
#[derive(Debug, Clone)]
pub struct TransactionBuilder {
version: u8,
network_id: u8,
gas_amount: u32,
gas_price: String,
inputs: Vec<AssetInput>,
outputs: Vec<AssetOutput>,
script: Option<String>,
}
impl TransactionBuilder {
pub fn new(network_id: u8) -> Self {
Self {
version: 0,
network_id,
gas_amount: 20_000, gas_price: "100000000000".to_string(), inputs: Vec::new(),
outputs: Vec::new(),
script: None,
}
}
pub fn version(mut self, version: u8) -> Self {
self.version = version;
self
}
pub fn gas_amount(mut self, gas_amount: u32) -> Self {
self.gas_amount = gas_amount;
self
}
pub fn gas_price(mut self, gas_price: impl Into<String>) -> Self {
self.gas_price = gas_price.into();
self
}
pub fn add_input(mut self, input: AssetInput) -> Self {
self.inputs.push(input);
self
}
pub fn add_inputs(mut self, inputs: Vec<AssetInput>) -> Self {
self.inputs.extend(inputs);
self
}
pub fn add_output(mut self, output: AssetOutput) -> Self {
self.outputs.push(output);
self
}
pub fn add_outputs(mut self, outputs: Vec<AssetOutput>) -> Self {
self.outputs.extend(outputs);
self
}
pub fn script(mut self, script: String) -> Self {
self.script = Some(script);
self
}
pub fn build(self) -> Result<UnsignedTransaction> {
if self.inputs.is_empty() {
return Err(Error::InvalidTransaction("No inputs provided".to_string()));
}
if self.outputs.is_empty() {
return Err(Error::InvalidTransaction("No outputs provided".to_string()));
}
use sha2::{Digest, Sha256};
let mut hasher = Sha256::new();
hasher.update(format!("{:?}", self));
let tx_id = hex::encode(hasher.finalize());
Ok(UnsignedTransaction {
tx_id,
version: self.version,
network_id: self.network_id,
gas_amount: self.gas_amount,
gas_price: self.gas_price,
inputs: self.inputs,
fixed_outputs: self.outputs,
script_opt: self.script,
})
}
}
pub struct TransactionSigner;
impl TransactionSigner {
pub fn sign(unsigned_tx: &UnsignedTransaction, private_key: &PrivateKey) -> Result<Transaction> {
let tx_bytes = serde_json::to_vec(unsigned_tx)
.map_err(|e| Error::SerializationError(e))?;
let signature = private_key.sign(&tx_bytes)?;
let signature_hex = hex::encode(signature.bytes());
Ok(Transaction {
unsigned: unsigned_tx.clone(),
script_execution_ok: true,
contract_inputs: Vec::new(),
generated_outputs: Vec::new(),
input_signatures: vec![signature_hex],
script_signatures: Vec::new(),
})
}
pub fn sign_with_keys(
unsigned_tx: &UnsignedTransaction,
private_keys: &[PrivateKey],
) -> Result<Transaction> {
let tx_bytes = serde_json::to_vec(unsigned_tx)
.map_err(|e| Error::SerializationError(e))?;
let mut signatures = Vec::new();
for private_key in private_keys {
let signature = private_key.sign(&tx_bytes)?;
signatures.push(hex::encode(signature.bytes()));
}
Ok(Transaction {
unsigned: unsigned_tx.clone(),
script_execution_ok: true,
contract_inputs: Vec::new(),
generated_outputs: Vec::new(),
input_signatures: signatures,
script_signatures: Vec::new(),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::signer::KeyType;
#[test]
fn test_asset_output_builder() {
let output = AssetOutput::new(
"1DrDyTr9RpRsQnDnXo2YRiPzPW4ooHX5LLoqXrqfMrpQH".to_string(),
"1000000000000000000".to_string(),
)
.with_lock_time(1234567890)
.with_message("test message".to_string());
assert_eq!(output.lock_time, Some(1234567890));
assert_eq!(output.message, Some("test message".to_string()));
}
#[test]
fn test_transaction_builder() {
let input = AssetInput {
output_ref: OutputRef {
hint: 0,
tx_hash: "0".repeat(64),
},
unlock_script: "".to_string(),
};
let output = AssetOutput::new(
"1DrDyTr9RpRsQnDnXo2YRiPzPW4ooHX5LLoqXrqfMrpQH".to_string(),
"1000000000000000000".to_string(),
);
let unsigned_tx = TransactionBuilder::new(0)
.gas_amount(20000)
.add_input(input)
.add_output(output)
.build()
.unwrap();
assert_eq!(unsigned_tx.network_id, 0);
assert_eq!(unsigned_tx.gas_amount, 20000);
assert_eq!(unsigned_tx.input_count(), 1);
assert_eq!(unsigned_tx.output_count(), 1);
}
#[test]
fn test_transaction_builder_no_inputs() {
let output = AssetOutput::new(
"1DrDyTr9RpRsQnDnXo2YRiPzPW4ooHX5LLoqXrqfMrpQH".to_string(),
"1000000000000000000".to_string(),
);
let result = TransactionBuilder::new(0).add_output(output).build();
assert!(result.is_err());
}
#[test]
fn test_transaction_signing() {
let private_key = PrivateKey::generate(KeyType::Secp256k1).unwrap();
let input = AssetInput {
output_ref: OutputRef {
hint: 0,
tx_hash: "0".repeat(64),
},
unlock_script: "".to_string(),
};
let output = AssetOutput::new(
"1DrDyTr9RpRsQnDnXo2YRiPzPW4ooHX5LLoqXrqfMrpQH".to_string(),
"1000000000000000000".to_string(),
);
let unsigned_tx = TransactionBuilder::new(0)
.add_input(input)
.add_output(output)
.build()
.unwrap();
let signed_tx = TransactionSigner::sign(&unsigned_tx, &private_key).unwrap();
assert_eq!(signed_tx.id(), unsigned_tx.id());
assert_eq!(signed_tx.input_signatures.len(), 1);
assert!(signed_tx.is_successful());
}
#[test]
fn test_multi_sig_transaction() {
let key1 = PrivateKey::generate(KeyType::Secp256k1).unwrap();
let key2 = PrivateKey::generate(KeyType::Ed25519).unwrap();
let input = AssetInput {
output_ref: OutputRef {
hint: 0,
tx_hash: "0".repeat(64),
},
unlock_script: "".to_string(),
};
let output = AssetOutput::new(
"1DrDyTr9RpRsQnDnXo2YRiPzPW4ooHX5LLoqXrqfMrpQH".to_string(),
"1000000000000000000".to_string(),
);
let unsigned_tx = TransactionBuilder::new(0)
.add_input(input)
.add_output(output)
.build()
.unwrap();
let signed_tx = TransactionSigner::sign_with_keys(&unsigned_tx, &[key1, key2]).unwrap();
assert_eq!(signed_tx.signature_count(), 2);
}
#[test]
fn test_total_output_amount() {
let input = AssetInput {
output_ref: OutputRef {
hint: 0,
tx_hash: "0".repeat(64),
},
unlock_script: "".to_string(),
};
let output1 = AssetOutput::new("addr1".to_string(), "1000000000000000000".to_string());
let output2 = AssetOutput::new("addr2".to_string(), "2000000000000000000".to_string());
let unsigned_tx = TransactionBuilder::new(0)
.add_input(input)
.add_outputs(vec![output1, output2])
.build()
.unwrap();
let total = unsigned_tx.total_output_amount().unwrap();
assert_eq!(total, 3000000000000000000u128);
}
}