This repository has been archived by the owner on Jun 11, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 77
/
transaction.rs
223 lines (187 loc) · 6.53 KB
/
transaction.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
use super::transfer::*;
use crate::key::Hash;
use crate::value::{Value, ValueError};
use chain_addr::Address;
use chain_core::mempack::{read_vec, ReadBuf, ReadError, Readable};
use chain_core::property;
// FIXME: should this be a wrapper type?
pub type TransactionId = Hash;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NoExtra;
impl property::Serialize for NoExtra {
type Error = std::io::Error;
fn serialize<W: std::io::Write>(&self, _: W) -> Result<(), Self::Error> {
Ok(())
}
}
impl property::Deserialize for NoExtra {
type Error = std::io::Error;
fn deserialize<R: std::io::BufRead>(_: R) -> Result<Self, Self::Error> {
Ok(NoExtra)
}
}
impl Readable for NoExtra {
fn read<'a>(_: &mut ReadBuf<'a>) -> Result<Self, ReadError> {
Ok(NoExtra)
}
}
/// Transaction, transaction maps old unspent tokens into the
/// set of the new addresses.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Transaction<OutAddress, Extra> {
pub inputs: Vec<Input>,
pub outputs: Vec<Output<OutAddress>>,
pub extra: Extra,
}
/// Amount of the balance in the transaction.
pub enum Balance {
/// Balance is positive.
Positive(Value),
/// Balance is negative, such transaction can't be valid.
Negative(Value),
/// Balance is zero.
Zero,
}
impl<Extra: Readable> Transaction<Address, Extra> {
fn read_body<'a>(
buf: &mut ReadBuf<'a>,
num_inputs: usize,
num_outputs: usize,
) -> Result<Self, ReadError> {
let inputs = read_vec(buf, num_inputs)?;
let outputs = read_vec(buf, num_outputs)?;
let extra = Extra::read(buf)?;
Ok(Transaction {
inputs,
outputs,
extra,
})
}
pub fn read_with_header<'a>(reader: &mut ReadBuf<'a>) -> Result<Self, ReadError> {
let num_inputs = reader.get_u8()? as usize;
let num_outputs = reader.get_u8()? as usize;
if !(num_inputs < 255) {
return Err(ReadError::SizeTooBig(num_inputs, 255));
}
if !(num_outputs < 255) {
return Err(ReadError::SizeTooBig(num_outputs, 255));
}
Self::read_body(reader, num_inputs, num_outputs)
}
}
impl<Extra: property::Serialize> Transaction<Address, Extra> {
fn serialize_body<W: std::io::Write>(&self, writer: &mut W) -> Result<(), Extra::Error> {
use chain_core::packer::*;
use chain_core::property::Serialize;
let mut codec = Codec::new(writer);
for input in self.inputs.iter() {
input.serialize(&mut codec)?;
}
for output in self.outputs.iter() {
output.address.serialize(&mut codec)?;
output.value.serialize(&mut codec)?;
}
self.extra.serialize(&mut codec)?;
Ok(())
}
pub fn serialize_with_header<W: std::io::Write>(&self, writer: W) -> Result<(), Extra::Error> {
use chain_core::packer::*;
assert!(self.inputs.len() < 255);
assert!(self.outputs.len() < 255);
let mut codec = Codec::new(writer);
// store the number of inputs and outputs
codec.put_u8(self.inputs.len() as u8)?;
codec.put_u8(self.outputs.len() as u8)?;
self.serialize_body(&mut codec.into_inner())
}
pub fn hash(&self) -> TransactionId {
let mut bytes = Vec::new();
self.serialize_body(&mut bytes).unwrap();
TransactionId::hash_bytes(&bytes)
}
}
impl<Extra: property::Deserialize> Transaction<Address, Extra> {
fn deserialize_body<R: std::io::BufRead>(
reader: R,
num_inputs: usize,
num_outputs: usize,
) -> Result<Self, Extra::Error> {
use chain_core::packer::*;
use chain_core::property::Deserialize as _;
let mut codec = Codec::new(reader);
let mut inputs = Vec::with_capacity(num_inputs);
let mut outputs = Vec::with_capacity(num_outputs);
for _ in 0..num_inputs {
let input = Input::deserialize(&mut codec)?;
inputs.push(input);
}
for _ in 0..num_outputs {
let address = Address::deserialize(&mut codec)?;
let value = Value::deserialize(&mut codec)?;
outputs.push(Output { address, value });
}
let extra = Extra::deserialize(&mut codec)?;
Ok(Transaction {
inputs,
outputs,
extra,
})
}
pub fn deserialize_with_header<R: std::io::BufRead>(reader: R) -> Result<Self, Extra::Error> {
use chain_core::packer::*;
let mut codec = Codec::new(reader);
let num_inputs = codec.get_u8()? as usize;
let num_outputs = codec.get_u8()? as usize;
if num_inputs < 255 && num_outputs < 255 {
Self::deserialize_body(codec.into_inner(), num_inputs, num_outputs)
} else {
// should return a nice error ...
panic!("deserialization with 256 inputs/outputs")
}
}
}
impl<Extra: property::Serialize> property::Serialize for Transaction<Address, Extra> {
type Error = Extra::Error;
fn serialize<W: std::io::Write>(&self, writer: W) -> Result<(), Extra::Error> {
self.serialize_with_header(writer)
}
}
impl<Extra: property::Deserialize> property::Deserialize for Transaction<Address, Extra> {
type Error = Extra::Error;
fn deserialize<R: std::io::BufRead>(reader: R) -> Result<Self, Extra::Error> {
Self::deserialize_with_header(reader)
}
}
impl<Extra: Readable> Readable for Transaction<Address, Extra> {
fn read<'a>(buf: &mut ReadBuf<'a>) -> Result<Self, ReadError> {
Self::read_with_header(buf)
}
}
impl<A, Extra> Transaction<A, Extra> {
pub fn replace_extra<Extra2>(self, e2: Extra2) -> Transaction<A, Extra2> {
Transaction {
inputs: self.inputs,
outputs: self.outputs,
extra: e2,
}
}
pub fn total_input(&self) -> Result<Value, ValueError> {
Value::sum(self.inputs.iter().map(|input| input.value))
}
pub fn total_output(&self) -> Result<Value, ValueError> {
Value::sum(self.outputs.iter().map(|output| output.value))
}
pub fn balance(&self, fee: Value) -> Result<Balance, ValueError> {
let inputs = self.total_input()?;
let outputs = self.total_output()?;
let z = (outputs + fee)?;
if inputs > z {
Ok(Balance::Positive((inputs - z)?))
} else if inputs < z {
Ok(Balance::Negative((z - inputs)?))
} else {
Ok(Balance::Zero)
}
}
}
impl property::TransactionId for TransactionId {}