forked from nervosnetwork/ckb
/
transaction.rs
446 lines (376 loc) · 10.7 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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
//! Transaction using Cell.
//! It is similar to Bitcoin Tx <https://en.bitcoin.it/wiki/Protocol_documentation#tx/>
use crate::script::Script;
pub use crate::Capacity;
use crate::{BlockNumber, Version};
use bincode::{deserialize, serialize};
use faster_hex::hex_string;
use hash::blake2b_256;
use numext_fixed_hash::H256;
use occupied_capacity::OccupiedCapacity;
use serde_derive::{Deserialize, Serialize};
use std::fmt;
use std::hash::{Hash, Hasher};
use std::ops::{Deref, DerefMut};
pub const TX_VERSION: Version = 0;
#[derive(Clone, Serialize, Deserialize, Eq, PartialEq, Hash, OccupiedCapacity)]
pub struct OutPoint {
// Hash of Transaction
pub hash: H256,
// Index of output
pub index: u32,
}
impl fmt::Debug for OutPoint {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("OutPoint")
.field("hash", &format_args!("{:#x}", self.hash))
.field("index", &self.index)
.finish()
}
}
impl Default for OutPoint {
fn default() -> Self {
OutPoint {
hash: H256::zero(),
index: u32::max_value(),
}
}
}
impl OutPoint {
pub fn new(hash: H256, index: u32) -> Self {
OutPoint { hash, index }
}
pub fn null() -> Self {
OutPoint::default()
}
pub fn is_null(&self) -> bool {
self.hash.is_zero() && self.index == u32::max_value()
}
pub fn destruct(self) -> (H256, u32) {
let OutPoint { hash, index } = self;
(hash, index)
}
}
#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, Debug, OccupiedCapacity)]
pub struct CellInput {
pub previous_output: OutPoint,
pub valid_since: u64,
// Depends on whether the operation is Transform or Destroy, this is the proof to transform
// lock or destroy lock.
pub args: Vec<Vec<u8>>,
}
impl CellInput {
pub fn new(previous_output: OutPoint, valid_since: u64, args: Vec<Vec<u8>>) -> Self {
CellInput {
previous_output,
valid_since,
args,
}
}
pub fn new_cellbase_input(block_number: BlockNumber) -> Self {
CellInput {
previous_output: OutPoint::null(),
valid_since: 0,
args: vec![block_number.to_le_bytes().to_vec()],
}
}
pub fn destruct(self) -> (OutPoint, u64, Vec<Vec<u8>>) {
let CellInput {
previous_output,
valid_since,
args,
} = self;
(previous_output, valid_since, args)
}
}
#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq, Hash, OccupiedCapacity)]
pub struct CellOutput {
pub capacity: Capacity,
#[serde(with = "serde_bytes")]
pub data: Vec<u8>,
pub lock: Script,
#[serde(rename = "type")]
pub type_: Option<Script>,
}
impl fmt::Debug for CellOutput {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("CellOutput")
.field("capacity", &self.capacity)
.field(
"data",
&format_args!("0x{}", &hex_string(&self.data).expect("hex data")),
)
.field("lock", &self.lock)
.field("type", &self.type_)
.finish()
}
}
impl CellOutput {
pub fn new(capacity: Capacity, data: Vec<u8>, lock: Script, type_: Option<Script>) -> Self {
CellOutput {
capacity,
data,
lock,
type_,
}
}
pub fn data_hash(&self) -> H256 {
blake2b_256(&self.data).into()
}
pub fn destruct(self) -> (Capacity, Vec<u8>, Script, Option<Script>) {
let CellOutput {
capacity,
data,
lock,
type_,
} = self;
(capacity, data, lock, type_)
}
}
pub type Witness = Vec<Vec<u8>>;
#[derive(Clone, Serialize, Deserialize, Eq, Debug, Default, OccupiedCapacity)]
pub struct Transaction {
version: Version,
deps: Vec<OutPoint>,
inputs: Vec<CellInput>,
outputs: Vec<CellOutput>,
//Segregated Witness to provide protection from transaction malleability.
witnesses: Vec<Witness>,
}
#[derive(Serialize)]
struct RawTransaction<'a> {
version: Version,
deps: &'a [OutPoint],
inputs: &'a [CellInput],
outputs: &'a [CellOutput],
}
impl Hash for Transaction {
fn hash<H: Hasher>(&self, state: &mut H) {
state.write(self.witness_hash().as_fixed_bytes())
}
}
impl PartialEq for Transaction {
fn eq(&self, other: &Transaction) -> bool {
self.witness_hash() == other.witness_hash()
}
}
impl Transaction {
pub fn version(&self) -> u32 {
self.version
}
pub fn deps(&self) -> &[OutPoint] {
&self.deps
}
pub fn inputs(&self) -> &[CellInput] {
&self.inputs
}
pub fn outputs(&self) -> &[CellOutput] {
&self.outputs
}
pub fn witnesses(&self) -> &[Witness] {
&self.witnesses
}
pub fn is_cellbase(&self) -> bool {
self.inputs.len() == 1 && self.inputs[0].previous_output.is_null()
}
pub fn hash(&self) -> H256 {
let raw = RawTransaction {
version: self.version,
deps: &self.deps,
inputs: &self.inputs,
outputs: &self.outputs,
};
blake2b_256(serialize(&raw).expect("Transaction serialize should not fail")).into()
}
pub fn witness_hash(&self) -> H256 {
blake2b_256(serialize(&self).expect("Transaction serialize should not fail")).into()
}
pub fn out_points_iter(&self) -> impl Iterator<Item = &OutPoint> {
self.deps.iter().chain(
self.inputs
.iter()
.map(|input: &CellInput| &input.previous_output),
)
}
pub fn output_pts(&self) -> Vec<OutPoint> {
let h = self.hash();
(0..self.outputs.len())
.map(|x| OutPoint::new(h.clone(), x as u32))
.collect()
}
pub fn input_pts(&self) -> Vec<OutPoint> {
self.inputs
.iter()
.map(|x| x.previous_output.clone())
.collect()
}
pub fn dep_pts(&self) -> Vec<OutPoint> {
self.deps.clone()
}
pub fn is_empty(&self) -> bool {
self.inputs.is_empty() || self.outputs.is_empty()
}
// proposal_short_id
pub fn proposal_short_id(&self) -> ProposalShortId {
ProposalShortId::from_tx_hash(&self.hash())
}
pub fn get_output(&self, i: usize) -> Option<CellOutput> {
self.outputs.get(i).cloned()
}
pub fn outputs_capacity(&self) -> Capacity {
self.outputs.iter().map(|output| output.capacity).sum()
}
}
#[derive(Default)]
pub struct TransactionBuilder {
inner: Transaction,
}
impl TransactionBuilder {
pub fn new(bytes: &[u8]) -> Self {
TransactionBuilder {
inner: deserialize(bytes).expect("transaction deserializing should be ok"),
}
}
pub fn transaction(mut self, transaction: Transaction) -> Self {
self.inner = transaction;
self
}
pub fn version(mut self, version: u32) -> Self {
self.inner.version = version;
self
}
pub fn dep(mut self, dep: OutPoint) -> Self {
self.inner.deps.push(dep);
self
}
pub fn deps(mut self, deps: Vec<OutPoint>) -> Self {
self.inner.deps.extend(deps);
self
}
pub fn deps_clear(mut self) -> Self {
self.inner.deps.clear();
self
}
pub fn input(mut self, input: CellInput) -> Self {
self.inner.inputs.push(input);
self
}
pub fn inputs(mut self, inputs: Vec<CellInput>) -> Self {
self.inner.inputs.extend(inputs);
self
}
pub fn inputs_clear(mut self) -> Self {
self.inner.inputs.clear();
self
}
pub fn output(mut self, output: CellOutput) -> Self {
self.inner.outputs.push(output);
self
}
pub fn outputs(mut self, outputs: Vec<CellOutput>) -> Self {
self.inner.outputs.extend(outputs);
self
}
pub fn outputs_clear(mut self) -> Self {
self.inner.outputs.clear();
self
}
pub fn witness(mut self, witness: Witness) -> Self {
self.inner.witnesses.push(witness);
self
}
pub fn witnesses(mut self, witness: Vec<Witness>) -> Self {
self.inner.witnesses.extend(witness);
self
}
pub fn witnesses_clear(mut self) -> Self {
self.inner.witnesses.clear();
self
}
pub fn build(self) -> Transaction {
self.inner
}
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct IndexTransaction {
pub index: usize,
pub transaction: Transaction,
}
#[derive(Serialize, Deserialize, Copy, Clone, PartialEq, Eq, Default, Hash)]
pub struct ProposalShortId([u8; 10]);
impl Deref for ProposalShortId {
type Target = [u8; 10];
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl fmt::Debug for ProposalShortId {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"ProposalShortId(0x{})",
hex_string(&self.0).expect("hex proposal short id")
)
}
}
impl DerefMut for ProposalShortId {
fn deref_mut(&mut self) -> &mut [u8; 10] {
&mut self.0
}
}
impl ProposalShortId {
pub fn new(inner: [u8; 10]) -> Self {
ProposalShortId(inner)
}
pub fn from_slice(slice: &[u8]) -> Option<Self> {
if slice.len() == 10usize {
let mut id = [0u8; 10];
id.copy_from_slice(slice);
Some(ProposalShortId(id))
} else {
None
}
}
pub fn from_tx_hash(h: &H256) -> Self {
let v = h.to_vec();
let mut inner = [0u8; 10];
inner.copy_from_slice(&v[..10]);
ProposalShortId(inner)
}
pub fn hash(&self) -> H256 {
blake2b_256(serialize(self).expect("ProposalShortId serialize should not fail")).into()
}
pub fn zero() -> Self {
ProposalShortId([0; 10])
}
pub fn into_inner(self) -> [u8; 10] {
self.0
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_tx_hash() {
let tx = TransactionBuilder::default()
.output(CellOutput::new(
5000,
vec![1, 2, 3],
Script::default(),
None,
))
.input(CellInput::new(OutPoint::new(H256::zero(), 0), vec![]))
.witness(vec![vec![7, 8, 9]])
.build();
assert_eq!(
tx.hash(),
H256::from_hex_str("3a4238c3fda565d6e76e76b5b05d3403b37b94d53c1644d5ff58d4e9293ca468")
.unwrap()
);
assert_eq!(
tx.witness_hash(),
H256::from_hex_str("997f0627d2c1ef00fc98311357aa097c3fff5ed0a0408e14ea26656f5beae6b3")
.unwrap()
);
}
}