1use crate::api::types::Token;
5use crate::error::{Error, Result};
6use crate::signer::PrivateKey;
7use serde::{Deserialize, Serialize};
8
9pub type TxId = String;
11
12#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
14pub struct OutputRef {
15 pub hint: i32,
16 #[serde(rename = "key")]
17 pub tx_hash: String,
18}
19
20#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
22pub struct AssetInput {
23 #[serde(rename = "outputRef")]
24 pub output_ref: OutputRef,
25 #[serde(rename = "unlockScript")]
26 pub unlock_script: String,
27}
28
29#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
31pub struct AssetOutput {
32 #[serde(rename = "address")]
33 pub address: String,
34 #[serde(rename = "attoAlphAmount")]
35 pub atto_alph_amount: String,
36 #[serde(skip_serializing_if = "Option::is_none")]
37 pub tokens: Option<Vec<Token>>,
38 #[serde(rename = "lockTime", skip_serializing_if = "Option::is_none")]
39 pub lock_time: Option<u64>,
40 #[serde(skip_serializing_if = "Option::is_none")]
41 pub message: Option<String>,
42}
43
44impl AssetOutput {
45 pub fn new(address: String, atto_alph_amount: String) -> Self {
47 Self {
48 address,
49 atto_alph_amount,
50 tokens: None,
51 lock_time: None,
52 message: None,
53 }
54 }
55
56 pub fn with_tokens(mut self, tokens: Vec<Token>) -> Self {
58 self.tokens = Some(tokens);
59 self
60 }
61
62 pub fn with_lock_time(mut self, lock_time: u64) -> Self {
64 self.lock_time = Some(lock_time);
65 self
66 }
67
68 pub fn with_message(mut self, message: String) -> Self {
70 self.message = Some(message);
71 self
72 }
73}
74
75#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
77pub struct ContractOutput {
78 #[serde(rename = "address")]
79 pub address: String,
80 #[serde(rename = "attoAlphAmount")]
81 pub atto_alph_amount: String,
82 #[serde(skip_serializing_if = "Option::is_none")]
83 pub tokens: Option<Vec<Token>>,
84}
85
86#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
88#[serde(tag = "type")]
89pub enum Output {
90 #[serde(rename = "AssetOutput")]
91 Asset(AssetOutput),
92 #[serde(rename = "ContractOutput")]
93 Contract(ContractOutput),
94}
95
96#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
98pub struct UnsignedTransaction {
99 #[serde(rename = "txId")]
100 pub tx_id: TxId,
101 pub version: u8,
102 #[serde(rename = "networkId")]
103 pub network_id: u8,
104 #[serde(rename = "gasAmount")]
105 pub gas_amount: u32,
106 #[serde(rename = "gasPrice")]
107 pub gas_price: String,
108 pub inputs: Vec<AssetInput>,
109 #[serde(rename = "fixedOutputs")]
110 pub fixed_outputs: Vec<AssetOutput>,
111 #[serde(rename = "scriptOpt", skip_serializing_if = "Option::is_none")]
112 pub script_opt: Option<String>,
113}
114
115impl UnsignedTransaction {
116 pub fn id(&self) -> &str {
118 &self.tx_id
119 }
120
121 pub fn input_count(&self) -> usize {
123 self.inputs.len()
124 }
125
126 pub fn output_count(&self) -> usize {
128 self.fixed_outputs.len()
129 }
130
131 pub fn total_output_amount(&self) -> Result<u128> {
133 let mut total = 0u128;
134 for output in &self.fixed_outputs {
135 let amount: u128 = output
136 .atto_alph_amount
137 .parse()
138 .map_err(|e| Error::InvalidValue(format!("Invalid amount: {}", e)))?;
139 total = total
140 .checked_add(amount)
141 .ok_or_else(|| Error::InvalidValue("Amount overflow".to_string()))?;
142 }
143 Ok(total)
144 }
145}
146
147#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
149pub struct Transaction {
150 pub unsigned: UnsignedTransaction,
151 #[serde(rename = "scriptExecutionOk")]
152 pub script_execution_ok: bool,
153 #[serde(rename = "contractInputs")]
154 pub contract_inputs: Vec<OutputRef>,
155 #[serde(rename = "generatedOutputs")]
156 pub generated_outputs: Vec<Output>,
157 #[serde(rename = "inputSignatures")]
158 pub input_signatures: Vec<String>,
159 #[serde(rename = "scriptSignatures")]
160 pub script_signatures: Vec<String>,
161}
162
163impl Transaction {
164 pub fn id(&self) -> &str {
166 self.unsigned.id()
167 }
168
169 pub fn is_successful(&self) -> bool {
171 self.script_execution_ok
172 }
173
174 pub fn signature_count(&self) -> usize {
176 self.input_signatures.len() + self.script_signatures.len()
177 }
178}
179
180#[derive(Debug, Clone)]
182pub struct TransactionBuilder {
183 version: u8,
184 network_id: u8,
185 gas_amount: u32,
186 gas_price: String,
187 inputs: Vec<AssetInput>,
188 outputs: Vec<AssetOutput>,
189 script: Option<String>,
190}
191
192impl TransactionBuilder {
193 pub fn new(network_id: u8) -> Self {
195 Self {
196 version: 0,
197 network_id,
198 gas_amount: 20_000, gas_price: "100000000000".to_string(), inputs: Vec::new(),
201 outputs: Vec::new(),
202 script: None,
203 }
204 }
205
206 pub fn version(mut self, version: u8) -> Self {
208 self.version = version;
209 self
210 }
211
212 pub fn gas_amount(mut self, gas_amount: u32) -> Self {
214 self.gas_amount = gas_amount;
215 self
216 }
217
218 pub fn gas_price(mut self, gas_price: impl Into<String>) -> Self {
220 self.gas_price = gas_price.into();
221 self
222 }
223
224 pub fn add_input(mut self, input: AssetInput) -> Self {
226 self.inputs.push(input);
227 self
228 }
229
230 pub fn add_inputs(mut self, inputs: Vec<AssetInput>) -> Self {
232 self.inputs.extend(inputs);
233 self
234 }
235
236 pub fn add_output(mut self, output: AssetOutput) -> Self {
238 self.outputs.push(output);
239 self
240 }
241
242 pub fn add_outputs(mut self, outputs: Vec<AssetOutput>) -> Self {
244 self.outputs.extend(outputs);
245 self
246 }
247
248 pub fn script(mut self, script: String) -> Self {
250 self.script = Some(script);
251 self
252 }
253
254 pub fn build(self) -> Result<UnsignedTransaction> {
256 if self.inputs.is_empty() {
257 return Err(Error::InvalidTransaction("No inputs provided".to_string()));
258 }
259
260 if self.outputs.is_empty() {
261 return Err(Error::InvalidTransaction("No outputs provided".to_string()));
262 }
263
264 use sha2::{Digest, Sha256};
266 let mut hasher = Sha256::new();
267 hasher.update(format!("{:?}", self));
268 let tx_id = hex::encode(hasher.finalize());
269
270 Ok(UnsignedTransaction {
271 tx_id,
272 version: self.version,
273 network_id: self.network_id,
274 gas_amount: self.gas_amount,
275 gas_price: self.gas_price,
276 inputs: self.inputs,
277 fixed_outputs: self.outputs,
278 script_opt: self.script,
279 })
280 }
281}
282
283pub struct TransactionSigner;
285
286impl TransactionSigner {
287 pub fn sign(unsigned_tx: &UnsignedTransaction, private_key: &PrivateKey) -> Result<Transaction> {
289 let tx_bytes = serde_json::to_vec(unsigned_tx)
291 .map_err(|e| Error::SerializationError(e))?;
292
293 let signature = private_key.sign(&tx_bytes)?;
295
296 let signature_hex = hex::encode(signature.bytes());
298
299 Ok(Transaction {
300 unsigned: unsigned_tx.clone(),
301 script_execution_ok: true,
302 contract_inputs: Vec::new(),
303 generated_outputs: Vec::new(),
304 input_signatures: vec![signature_hex],
305 script_signatures: Vec::new(),
306 })
307 }
308
309 pub fn sign_with_keys(
311 unsigned_tx: &UnsignedTransaction,
312 private_keys: &[PrivateKey],
313 ) -> Result<Transaction> {
314 let tx_bytes = serde_json::to_vec(unsigned_tx)
315 .map_err(|e| Error::SerializationError(e))?;
316
317 let mut signatures = Vec::new();
318 for private_key in private_keys {
319 let signature = private_key.sign(&tx_bytes)?;
320 signatures.push(hex::encode(signature.bytes()));
321 }
322
323 Ok(Transaction {
324 unsigned: unsigned_tx.clone(),
325 script_execution_ok: true,
326 contract_inputs: Vec::new(),
327 generated_outputs: Vec::new(),
328 input_signatures: signatures,
329 script_signatures: Vec::new(),
330 })
331 }
332}
333
334#[cfg(test)]
335mod tests {
336 use super::*;
337 use crate::signer::KeyType;
338
339 #[test]
340 fn test_asset_output_builder() {
341 let output = AssetOutput::new(
342 "1DrDyTr9RpRsQnDnXo2YRiPzPW4ooHX5LLoqXrqfMrpQH".to_string(),
343 "1000000000000000000".to_string(),
344 )
345 .with_lock_time(1234567890)
346 .with_message("test message".to_string());
347
348 assert_eq!(output.lock_time, Some(1234567890));
349 assert_eq!(output.message, Some("test message".to_string()));
350 }
351
352 #[test]
353 fn test_transaction_builder() {
354 let input = AssetInput {
355 output_ref: OutputRef {
356 hint: 0,
357 tx_hash: "0".repeat(64),
358 },
359 unlock_script: "".to_string(),
360 };
361
362 let output = AssetOutput::new(
363 "1DrDyTr9RpRsQnDnXo2YRiPzPW4ooHX5LLoqXrqfMrpQH".to_string(),
364 "1000000000000000000".to_string(),
365 );
366
367 let unsigned_tx = TransactionBuilder::new(0)
368 .gas_amount(20000)
369 .add_input(input)
370 .add_output(output)
371 .build()
372 .unwrap();
373
374 assert_eq!(unsigned_tx.network_id, 0);
375 assert_eq!(unsigned_tx.gas_amount, 20000);
376 assert_eq!(unsigned_tx.input_count(), 1);
377 assert_eq!(unsigned_tx.output_count(), 1);
378 }
379
380 #[test]
381 fn test_transaction_builder_no_inputs() {
382 let output = AssetOutput::new(
383 "1DrDyTr9RpRsQnDnXo2YRiPzPW4ooHX5LLoqXrqfMrpQH".to_string(),
384 "1000000000000000000".to_string(),
385 );
386
387 let result = TransactionBuilder::new(0).add_output(output).build();
388
389 assert!(result.is_err());
390 }
391
392 #[test]
393 fn test_transaction_signing() {
394 let private_key = PrivateKey::generate(KeyType::Secp256k1).unwrap();
395
396 let input = AssetInput {
397 output_ref: OutputRef {
398 hint: 0,
399 tx_hash: "0".repeat(64),
400 },
401 unlock_script: "".to_string(),
402 };
403
404 let output = AssetOutput::new(
405 "1DrDyTr9RpRsQnDnXo2YRiPzPW4ooHX5LLoqXrqfMrpQH".to_string(),
406 "1000000000000000000".to_string(),
407 );
408
409 let unsigned_tx = TransactionBuilder::new(0)
410 .add_input(input)
411 .add_output(output)
412 .build()
413 .unwrap();
414
415 let signed_tx = TransactionSigner::sign(&unsigned_tx, &private_key).unwrap();
416
417 assert_eq!(signed_tx.id(), unsigned_tx.id());
418 assert_eq!(signed_tx.input_signatures.len(), 1);
419 assert!(signed_tx.is_successful());
420 }
421
422 #[test]
423 fn test_multi_sig_transaction() {
424 let key1 = PrivateKey::generate(KeyType::Secp256k1).unwrap();
425 let key2 = PrivateKey::generate(KeyType::Ed25519).unwrap();
426
427 let input = AssetInput {
428 output_ref: OutputRef {
429 hint: 0,
430 tx_hash: "0".repeat(64),
431 },
432 unlock_script: "".to_string(),
433 };
434
435 let output = AssetOutput::new(
436 "1DrDyTr9RpRsQnDnXo2YRiPzPW4ooHX5LLoqXrqfMrpQH".to_string(),
437 "1000000000000000000".to_string(),
438 );
439
440 let unsigned_tx = TransactionBuilder::new(0)
441 .add_input(input)
442 .add_output(output)
443 .build()
444 .unwrap();
445
446 let signed_tx = TransactionSigner::sign_with_keys(&unsigned_tx, &[key1, key2]).unwrap();
447
448 assert_eq!(signed_tx.signature_count(), 2);
449 }
450
451 #[test]
452 fn test_total_output_amount() {
453 let input = AssetInput {
454 output_ref: OutputRef {
455 hint: 0,
456 tx_hash: "0".repeat(64),
457 },
458 unlock_script: "".to_string(),
459 };
460
461 let output1 = AssetOutput::new("addr1".to_string(), "1000000000000000000".to_string());
462 let output2 = AssetOutput::new("addr2".to_string(), "2000000000000000000".to_string());
463
464 let unsigned_tx = TransactionBuilder::new(0)
465 .add_input(input)
466 .add_outputs(vec![output1, output2])
467 .build()
468 .unwrap();
469
470 let total = unsigned_tx.total_output_amount().unwrap();
471 assert_eq!(total, 3000000000000000000u128);
472 }
473}