forked from ElementsProject/rust-elements
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtransaction.rs
More file actions
2534 lines (2330 loc) · 136 KB
/
transaction.rs
File metadata and controls
2534 lines (2330 loc) · 136 KB
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Rust Elements Library
// Written in 2018 by
// Andrew Poelstra <apoelstra@blockstream.com>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication
// along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
//
//! # Transactions
//!
use std::{io, fmt, str, cmp};
use std::collections::HashMap;
use std::convert::TryFrom;
use bitcoin::{self, VarInt};
use crate::hashes::{Hash, sha256};
use crate::{confidential, ContractHash};
use crate::encode::{self, Encodable, Decodable};
use crate::issuance::AssetId;
use crate::opcodes;
use crate::parse::impl_parse_str_through_int;
use crate::script::Instruction;
use crate::{LockTime, Script, Txid, Wtxid};
use secp256k1_zkp::{
RangeProof, SurjectionProof, Tweak, ZERO_TWEAK,
};
/// Description of an asset issuance in a transaction input
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub struct AssetIssuance {
/// Zero for a new asset issuance; otherwise a blinding factor for the input
pub asset_blinding_nonce: Tweak,
/// Freeform entropy field
pub asset_entropy: [u8; 32],
/// Amount of asset to issue
pub amount: confidential::Value,
/// Amount of inflation keys to issue
pub inflation_keys: confidential::Value,
}
impl AssetIssuance {
/// Create a null issuance.
pub fn null() -> Self {
AssetIssuance {
asset_blinding_nonce: ZERO_TWEAK,
asset_entropy: [0; 32],
amount: confidential::Value::Null,
inflation_keys: confidential::Value::Null,
}
}
/// Checks whether the [`AssetIssuance`] is null
pub fn is_null(&self) -> bool {
self.amount.is_null() && self.inflation_keys.is_null()
}
}
serde_struct_impl!(AssetIssuance, asset_blinding_nonce, asset_entropy, amount, inflation_keys);
impl_consensus_encoding!(AssetIssuance, asset_blinding_nonce, asset_entropy, amount, inflation_keys);
impl Default for AssetIssuance {
fn default() -> Self {
Self::null()
}
}
/// A reference to a transaction output
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
pub struct OutPoint {
/// The referenced transaction's txid
pub txid: Txid,
/// The index of the referenced output in its transaction's vout
pub vout: u32,
}
serde_struct_human_string_impl!(OutPoint, "an Elements OutPoint", txid, vout);
impl OutPoint {
/// Create a new outpoint.
#[inline]
pub fn new(txid: Txid, vout: u32) -> OutPoint {
OutPoint {
txid,
vout,
}
}
/// Creates a "null" `OutPoint`.
///
/// This value is used for coinbase transactions because they don't have
/// any previous outputs.
#[inline]
pub fn null() -> OutPoint {
OutPoint {
txid: Txid::all_zeros(),
vout: u32::MAX,
}
}
/// Checks if an `OutPoint` is "null".
#[inline]
pub fn is_null(&self) -> bool {
*self == OutPoint::null()
}
}
impl Default for OutPoint {
/// Coinbase outpoint
fn default() -> OutPoint {
OutPoint::null()
}
}
impl Encodable for OutPoint {
fn consensus_encode<S: io::Write>(&self, mut s: S) -> Result<usize, encode::Error> {
Ok(self.txid.consensus_encode(&mut s)? +
self.vout.consensus_encode(&mut s)?)
}
}
impl Decodable for OutPoint {
fn consensus_decode<D: io::Read>(mut d: D) -> Result<OutPoint, encode::Error> {
let txid = Txid::consensus_decode(&mut d)?;
let vout = u32::consensus_decode(&mut d)?;
Ok(OutPoint {
txid,
vout,
})
}
}
impl fmt::Display for OutPoint {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("[elements]")?;
write!(f, "{}:{}", self.txid, self.vout)
}
}
impl ::std::str::FromStr for OutPoint {
type Err = bitcoin::blockdata::transaction::ParseOutPointError;
fn from_str(mut s: &str) -> Result<Self, Self::Err> {
if s.starts_with("[elements]") {
s = &s[10..];
}
let bitcoin_outpoint = bitcoin::OutPoint::from_str(s)?;
Ok(OutPoint {
txid: Txid::from(bitcoin_outpoint.txid.to_raw_hash()),
vout: bitcoin_outpoint.vout,
})
}
}
/// Bitcoin transaction input sequence number.
///
/// The sequence field is used for:
/// - Indicating whether absolute lock-time (specified in `lock_time` field of [`Transaction`])
/// is enabled.
/// - Indicating and encoding [BIP-68] relative lock-times.
/// - Indicating whether a transaction opts-in to [BIP-125] replace-by-fee.
///
/// Note that transactions spending an output with `OP_CHECKLOCKTIMEVERIFY`MUST NOT use
/// `Sequence::MAX` for the corresponding input. [BIP-65]
///
/// [BIP-65]: <https://github.com/bitcoin/bips/blob/master/bip-0065.mediawiki>
/// [BIP-68]: <https://github.com/bitcoin/bips/blob/master/bip-0068.mediawiki>
/// [BIP-125]: <https://github.com/bitcoin/bips/blob/master/bip-0125.mediawiki>
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
pub struct Sequence(pub u32);
#[derive(Clone, PartialEq, Eq, Debug)]
#[non_exhaustive]
/// An error in creating relative lock-times.
pub enum RelativeLockTimeError {
/// The input was too large
IntegerOverflow(u32)
}
impl Sequence {
/// The maximum allowable sequence number.
///
/// This sequence number disables lock-time and replace-by-fee.
pub const MAX: Self = Sequence(0xFFFF_FFFF);
/// Zero value sequence.
///
/// This sequence number enables replace-by-fee and lock-time.
pub const ZERO: Self = Sequence(0);
/// The sequence number that enables absolute lock-time but disables replace-by-fee
/// and relative lock-time.
pub const ENABLE_LOCKTIME_NO_RBF: Self = Sequence::MIN_NO_RBF;
/// The sequence number that enables replace-by-fee and absolute lock-time but
/// disables relative lock-time.
pub const ENABLE_RBF_NO_LOCKTIME: Self = Sequence(0xFFFF_FFFD);
/// The lowest sequence number that does not opt-in for replace-by-fee.
///
/// A transaction is considered to have opted in to replacement of itself
/// if any of it's inputs have a `Sequence` number less than this value
/// (Explicit Signalling [BIP-125]).
///
/// [BIP-125]: <https://github.com/bitcoin/bips/blob/master/bip-0125.mediawiki]>
const MIN_NO_RBF: Self = Sequence(0xFFFF_FFFE);
/// BIP-68 relative lock-time disable flag mask
const LOCK_TIME_DISABLE_FLAG_MASK: u32 = 0x8000_0000;
/// BIP-68 relative lock-time type flag mask
const LOCK_TYPE_MASK: u32 = 0x0040_0000;
/// Returns `true` if the sequence number indicates that the transaction is finalised.
///
/// The sequence number being equal to 0xffffffff on all txin sequences indicates
/// that the transaction is finalised.
#[inline]
pub fn is_final(&self) -> bool {
*self == Sequence::MAX
}
/// Returns true if the transaction opted-in to BIP125 replace-by-fee.
///
/// Replace by fee is signaled by the sequence being less than 0xfffffffe which is checked by this method.
#[inline]
pub fn is_rbf(&self) -> bool {
*self < Sequence::MIN_NO_RBF
}
/// Returns `true` if the sequence has a relative lock-time.
#[inline]
pub fn is_relative_lock_time(&self) -> bool {
self.0 & Sequence::LOCK_TIME_DISABLE_FLAG_MASK == 0
}
/// Returns `true` if the sequence number encodes a block based relative lock-time.
#[inline]
pub fn is_height_locked(&self) -> bool {
self.is_relative_lock_time() & (self.0 & Sequence::LOCK_TYPE_MASK == 0)
}
/// Returns `true` if the sequence number encodes a time interval based relative lock-time.
#[inline]
pub fn is_time_locked(&self) -> bool {
self.is_relative_lock_time() & (self.0 & Sequence::LOCK_TYPE_MASK > 0)
}
/// Create a relative lock-time using block height.
#[inline]
pub fn from_height(height: u16) -> Self {
Sequence(u32::from(height))
}
/// Create a relative lock-time using time intervals where each interval is equivalent
/// to 512 seconds.
///
/// Encoding finer granularity of time for relative lock-times is not supported in Bitcoin
#[inline]
pub fn from_512_second_intervals(intervals: u16) -> Self {
Sequence(u32::from(intervals) | Sequence::LOCK_TYPE_MASK)
}
/// Create a relative lock-time from seconds, converting the seconds into 512 second
/// interval with floor division.
///
/// Will return an error if the input cannot be encoded in 16 bits.
#[inline]
pub fn from_seconds_floor(seconds: u32) -> Result<Self, RelativeLockTimeError> {
if let Ok(interval) = u16::try_from(seconds / 512) {
Ok(Sequence::from_512_second_intervals(interval))
} else {
Err(RelativeLockTimeError::IntegerOverflow(seconds))
}
}
/// Create a relative lock-time from seconds, converting the seconds into 512 second
/// interval with ceiling division.
///
/// Will return an error if the input cannot be encoded in 16 bits.
#[inline]
pub fn from_seconds_ceil(seconds: u32) -> Result<Self, RelativeLockTimeError> {
if let Ok(interval) = u16::try_from((seconds + 511) / 512) {
Ok(Sequence::from_512_second_intervals(interval))
} else {
Err(RelativeLockTimeError::IntegerOverflow(seconds))
}
}
/// Returns `true` if the sequence number enables absolute lock-time ([`Transaction::lock_time`]).
#[inline]
pub fn enables_absolute_lock_time(&self) -> bool {
!self.is_final()
}
/// Create a sequence from a u32 value.
#[inline]
pub fn from_consensus(n: u32) -> Self {
Sequence(n)
}
/// Returns the inner 32bit integer value of Sequence.
#[inline]
pub fn to_consensus_u32(self) -> u32 {
self.0
}
}
impl Default for Sequence {
/// The default value of sequence is 0xffffffff.
fn default() -> Self {
Sequence::MAX
}
}
impl From<Sequence> for u32 {
fn from(sequence: Sequence) -> u32 {
sequence.0
}
}
impl fmt::Display for Sequence {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
impl fmt::LowerHex for Sequence {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::LowerHex::fmt(&self.0, f)
}
}
impl fmt::UpperHex for Sequence {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::UpperHex::fmt(&self.0, f)
}
}
impl fmt::Display for RelativeLockTimeError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Self::IntegerOverflow(val) => write!(f, "input of {} was too large", val)
}
}
}
impl_parse_str_through_int!(Sequence);
impl std::error::Error for RelativeLockTimeError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::IntegerOverflow(_) => None
}
}
}
/// Transaction input witness
#[derive(Clone, PartialEq, Eq, Debug, Hash, PartialOrd, Ord)]
pub struct TxInWitness {
/// Amount rangeproof
pub amount_rangeproof: Option<Box<RangeProof>>,
/// Rangeproof for inflation keys
pub inflation_keys_rangeproof: Option<Box<RangeProof>>,
/// Traditional script witness
pub script_witness: Vec<Vec<u8>>,
/// Pegin witness, basically the same thing
pub pegin_witness: Vec<Vec<u8>>,
}
serde_struct_impl!(TxInWitness, amount_rangeproof, inflation_keys_rangeproof, script_witness, pegin_witness);
impl_consensus_encoding!(TxInWitness, amount_rangeproof, inflation_keys_rangeproof, script_witness, pegin_witness);
impl TxInWitness {
/// Create an empty input witness.
pub fn empty() -> Self {
TxInWitness {
amount_rangeproof: None,
inflation_keys_rangeproof: None,
script_witness: Vec::new(),
pegin_witness: Vec::new(),
}
}
/// Whether this witness is null
pub fn is_empty(&self) -> bool {
self.amount_rangeproof.is_none() &&
self.inflation_keys_rangeproof.is_none() &&
self.script_witness.is_empty() &&
self.pegin_witness.is_empty()
}
}
impl Default for TxInWitness {
fn default() -> Self {
Self::empty()
}
}
/// Parsed data from a transaction input's pegin witness
#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
pub struct PeginData<'tx> {
/// Reference to the pegin output on the mainchain
pub outpoint: bitcoin::OutPoint,
/// The value, in satoshis, of the pegin
pub value: u64,
/// Asset type being pegged in
pub asset: AssetId,
/// Hash of genesis block of originating blockchain
pub genesis_hash: bitcoin::BlockHash,
/// The claim script that we should hash to tweak our address. Unparsed
/// to avoid unnecessary allocation and copying. Typical use is simply
/// to feed it raw into a hash function.
pub claim_script: &'tx [u8],
/// Mainchain transaction; not parsed to save time/memory since the
/// parsed transaction is typically not useful without auxiliary
/// data (e.g. knowing how to compute pegin addresses for the
/// sidechain).
pub tx: &'tx [u8],
/// Merkle proof of transaction inclusion; also not parsed
pub merkle_proof: &'tx [u8],
/// The Bitcoin block that the pegin output appears in; scraped
/// from the transaction inclusion proof
pub referenced_block: bitcoin::BlockHash,
}
impl<'tx> PeginData<'tx> {
/// Construct the pegin data from a pegin witness.
/// Returns None if not a valid pegin witness.
pub fn from_pegin_witness(
pegin_witness: &'tx [Vec<u8>],
prevout: bitcoin::OutPoint,
) -> Result<PeginData<'tx>, &'static str> {
if pegin_witness.len() != 6 {
return Err("size not 6");
}
if pegin_witness[5].len() < 80 {
return Err("merkle proof too short");
}
Ok(PeginData {
outpoint: prevout,
value: bitcoin::consensus::deserialize(&pegin_witness[0]).map_err(|_| "invalid value")?,
asset: encode::deserialize(&pegin_witness[1]).map_err(|_| "invalid asset")?,
genesis_hash: bitcoin::consensus::deserialize(&pegin_witness[2])
.map_err(|_| "invalid genesis hash")?,
claim_script: &pegin_witness[3],
tx: &pegin_witness[4],
merkle_proof: &pegin_witness[5],
referenced_block: bitcoin::BlockHash::hash(&pegin_witness[5][0..80]),
})
}
/// Construct a pegin witness from the pegin data.
pub fn to_pegin_witness(&self) -> Vec<Vec<u8>> {
vec![
bitcoin::consensus::serialize(&self.value),
encode::serialize(&self.asset),
bitcoin::consensus::serialize(&self.genesis_hash),
self.claim_script.to_vec(),
self.tx.to_vec(),
self.merkle_proof.to_vec(),
]
}
/// Parse the mainchain tx provided as pegin data.
pub fn parse_tx(&self) -> Result<bitcoin::Transaction, bitcoin::consensus::encode::Error> {
bitcoin::consensus::encode::deserialize(self.tx)
}
/// Parse the merkle inclusion proof provided as pegin data.
pub fn parse_merkle_proof(&self) -> Result<bitcoin::MerkleBlock, bitcoin::consensus::encode::Error> {
bitcoin::consensus::encode::deserialize(self.merkle_proof)
}
}
/// A transaction input, which defines old coins to be consumed
#[derive(Clone, PartialEq, Eq, Debug, Hash, PartialOrd, Ord)]
pub struct TxIn {
/// The reference to the previous output that is being used as an input
pub previous_output: OutPoint,
/// Flag indicating that `previous_outpoint` refers to something on the main chain
pub is_pegin: bool,
/// The script which pushes values on the stack which will cause
/// the referenced output's script to accept
pub script_sig: Script,
/// The sequence number, which suggests to miners which of two
/// conflicting transactions should be preferred, or 0xFFFFFFFF
/// to ignore this feature. This is generally never used since
/// the miner behaviour cannot be enforced.
pub sequence: Sequence,
/// Asset issuance data
pub asset_issuance: AssetIssuance,
/// Witness data - not deserialized/serialized as part of a `TxIn` object
/// (rather as part of its containing transaction, if any) but is logically
/// part of the txin.
pub witness: TxInWitness,
}
impl Default for TxIn {
fn default() -> Self {
Self {
previous_output: OutPoint::default(), // same as in rust-bitcoin
is_pegin: false,
script_sig: Script::new(),
sequence: Sequence::MAX, // same as in rust-bitcoin
asset_issuance: AssetIssuance::default(),
witness: TxInWitness::default()
}
}
}
serde_struct_impl!(TxIn, previous_output, is_pegin, script_sig, sequence, asset_issuance, witness);
impl Encodable for TxIn {
fn consensus_encode<S: io::Write>(&self, mut s: S) -> Result<usize, encode::Error> {
let mut ret = 0;
let mut vout = self.previous_output.vout;
if self.is_pegin {
vout |= 1 << 30;
}
if self.has_issuance() {
vout |= 1 << 31;
}
ret += self.previous_output.txid.consensus_encode(&mut s)?;
ret += vout.consensus_encode(&mut s)?;
ret += self.script_sig.consensus_encode(&mut s)?;
ret += self.sequence.consensus_encode(&mut s)?;
if self.has_issuance() {
ret += self.asset_issuance.consensus_encode(&mut s)?;
}
Ok(ret)
}
}
impl Decodable for TxIn {
fn consensus_decode<D: io::Read>(mut d: D) -> Result<TxIn, encode::Error> {
let mut outp = OutPoint::consensus_decode(&mut d)?;
let script_sig = Script::consensus_decode(&mut d)?;
let sequence = Sequence::consensus_decode(&mut d)?;
let issuance;
let is_pegin;
let has_issuance;
// Pegin/issuance flags are encoded into the high bits of `vout`, *except*
// if vout is all 1's; this indicates a coinbase transaction
if outp.vout == 0xffff_ffff {
is_pegin = false;
has_issuance = false;
} else {
is_pegin = outp.vout & (1 << 30) != 0;
has_issuance = outp.vout & (1 << 31) != 0;
outp.vout &= !((1 << 30) | (1 << 31));
}
if has_issuance {
issuance = AssetIssuance::consensus_decode(&mut d)?;
if issuance.is_null() {
return Err(encode::Error::ParseFailed("superfluous asset issuance"));
}
} else {
issuance = AssetIssuance::default();
}
Ok(TxIn {
previous_output: outp,
is_pegin,
script_sig,
sequence,
asset_issuance: issuance,
witness: TxInWitness::default(),
})
}
}
impl TxIn {
/// Whether the input is a coinbase
pub fn is_coinbase(&self) -> bool {
self.previous_output == OutPoint::default()
}
/// Whether the input is a pegin
pub fn is_pegin(&self) -> bool {
self.is_pegin
}
/// In case of a pegin input, returns the Bitcoin prevout.
pub fn pegin_prevout(&self) -> Option<bitcoin::OutPoint> {
if self.is_pegin {
// here we have to cast the previous_output to a bitcoin one
Some(bitcoin::OutPoint {
txid: bitcoin::Txid::from_byte_array(
self.previous_output.txid.to_byte_array()
),
vout: self.previous_output.vout,
})
} else {
None
}
}
/// Extracts witness data from a pegin. Will return `None` if any data
/// cannot be parsed. The combination of `is_pegin()` returning `true`
/// and `pegin_data()` returning `None` indicates an invalid transaction.
pub fn pegin_data(&self) -> Option<PeginData<'_>> {
self.pegin_prevout().and_then(|p| {
PeginData::from_pegin_witness(&self.witness.pegin_witness, p).ok()
})
}
/// Helper to determine whether an input has an asset issuance attached
pub fn has_issuance(&self) -> bool {
!&self.asset_issuance.is_null()
}
/// Obtain the outpoint flag corresponding to this input
pub fn outpoint_flag(&self) -> u8 {
(u8::from(self.is_pegin) << 6) | (u8::from(self.has_issuance()) << 7)
}
/// Compute the issuance asset ids from this [`TxIn`]. This function does not check
/// whether there is an issuance in this input. Returns (`asset_id`, `token_id`)
pub fn issuance_ids(&self) -> (AssetId, AssetId) {
let entropy = if self.asset_issuance.asset_blinding_nonce == ZERO_TWEAK {
let contract_hash =
ContractHash::from_byte_array(self.asset_issuance.asset_entropy);
AssetId::generate_asset_entropy(self.previous_output, contract_hash)
} else {
// re-issuance
sha256::Midstate::from_byte_array(self.asset_issuance.asset_entropy)
};
let asset_id = AssetId::from_entropy(entropy);
let token_id =
AssetId::reissuance_token_from_entropy(entropy, self.asset_issuance.amount.is_confidential());
(asset_id, token_id)
}
}
/// Transaction output witness
#[derive(Clone, PartialEq, Eq, Debug, Hash, PartialOrd, Ord)]
pub struct TxOutWitness {
/// Surjection proof showing that the asset commitment is legitimate
// We Box it because surjection proof internally is an array [u8; N] that
// allocates on stack even when the surjection proof is empty
pub surjection_proof: Option<Box<SurjectionProof>>,
/// Rangeproof showing that the value commitment is legitimate
// We Box it because range proof internally is an array [u8; N] that
// allocates on stack even when the range proof is empty
pub rangeproof: Option<Box<RangeProof>>,
}
serde_struct_impl!(TxOutWitness, surjection_proof, rangeproof);
impl_consensus_encoding!(TxOutWitness, surjection_proof, rangeproof);
impl TxOutWitness {
/// Create an empty output witness.
pub fn empty() -> Self {
TxOutWitness {
surjection_proof: None,
rangeproof: None,
}
}
/// Whether this witness is null
pub fn is_empty(&self) -> bool {
self.surjection_proof.is_none() && self.rangeproof.is_none()
}
/// The rangeproof len if is present, otherwise 0
pub fn rangeproof_len(&self) -> usize {
self.rangeproof.as_ref().map_or(0, |prf| prf.len())
}
/// The surjection proof len if is present, otherwise 0
pub fn surjectionproof_len(&self) -> usize {
self.surjection_proof.as_ref().map_or(0, |prf| prf.len())
}
}
impl Default for TxOutWitness {
fn default() -> Self {
Self::empty()
}
}
/// Information about a pegout
#[derive(Clone, PartialEq, Eq, Debug, Hash)]
pub struct PegoutData<'txo> {
/// Amount to peg out
pub value: u64,
/// Asset of pegout
pub asset: confidential::Asset,
/// Genesis hash of the target blockchain
pub genesis_hash: bitcoin::BlockHash,
/// Scriptpubkey to create on the target blockchain
pub script_pubkey: bitcoin::ScriptBuf,
/// Remaining pegout data used by some forks of Elements
pub extra_data: Vec<&'txo [u8]>,
}
/// Transaction output
#[derive(Clone, Default, PartialEq, Eq, Debug, Hash, PartialOrd, Ord)]
pub struct TxOut {
/// Committed asset
pub asset: confidential::Asset,
/// Committed amount
pub value: confidential::Value,
/// Nonce (ECDH key passed to recipient)
pub nonce: confidential::Nonce,
/// Scriptpubkey
pub script_pubkey: Script,
/// Witness data - not deserialized/serialized as part of a `TxIn` object
/// (rather as part of its containing transaction, if any) but is logically
/// part of the txin.
pub witness: TxOutWitness,
}
serde_struct_impl!(TxOut, asset, value, nonce, script_pubkey, witness);
impl Encodable for TxOut {
fn consensus_encode<S: io::Write>(&self, mut s: S) -> Result<usize, encode::Error> {
Ok(self.asset.consensus_encode(&mut s)? +
self.value.consensus_encode(&mut s)? +
self.nonce.consensus_encode(&mut s)? +
self.script_pubkey.consensus_encode(&mut s)?)
}
}
impl Decodable for TxOut {
fn consensus_decode<D: io::Read>(mut d: D) -> Result<TxOut, encode::Error> {
Ok(TxOut {
asset: Decodable::consensus_decode(&mut d)?,
value: Decodable::consensus_decode(&mut d)?,
nonce: Decodable::consensus_decode(&mut d)?,
script_pubkey: Decodable::consensus_decode(&mut d)?,
witness: TxOutWitness::default(),
})
}
}
impl TxOut {
/// Create a new fee output.
pub fn new_fee(amount: u64, asset: AssetId) -> TxOut {
TxOut {
asset: confidential::Asset::Explicit(asset),
value: confidential::Value::Explicit(amount),
nonce: confidential::Nonce::Null,
script_pubkey: Script::new(),
witness: TxOutWitness::default(),
}
}
/// Whether this data represents nulldata (`OP_RETURN` followed by pushes,
/// not necessarily minimal)
pub fn is_null_data(&self) -> bool {
let mut iter = self.script_pubkey.instructions();
if iter.next() == Some(Ok(Instruction::Op(opcodes::all::OP_RETURN))) {
for push in iter {
match push {
Ok(Instruction::Op(op)) if op.into_u8() > opcodes::all::OP_PUSHNUM_16.into_u8() => return false,
Err(_) => return false,
_ => {}
}
}
true
} else {
false
}
}
/// Whether this output is a pegout, which is a subset of nulldata with the
/// following extra rules: (a) there must be at least 2 pushes, the first of
/// which must be 32 bytes and the second of which must be nonempty; (b) all
/// pushes must use a push opcode rather than a numeric or reserved opcode
pub fn is_pegout(&self) -> bool {
self.pegout_data().is_some()
}
/// If this output is a pegout, returns the destination genesis block,
/// the destination script pubkey, and any additional data
pub fn pegout_data(&self) -> Option<PegoutData<'_>> {
// Must be NULLDATA
if !self.is_null_data() {
return None;
}
// Must have an explicit value
let value = self.value.explicit()?;
let mut iter = self.script_pubkey.instructions();
iter.next(); // Skip OP_RETURN
// Parse destination chain's genesis block
let genesis_hash = bitcoin::BlockHash::from_raw_hash(
crate::hashes::Hash::from_slice(iter.next()?.ok()?.push_bytes()?).ok()?
);
// Parse destination scriptpubkey
let script_pubkey = bitcoin::ScriptBuf::from(iter.next()?.ok()?.push_bytes()?.to_owned());
if script_pubkey.is_empty() {
return None;
}
// Return everything
let mut found_non_data_push = false;
let remainder = iter
.filter_map(|x| if let Ok(Instruction::PushBytes(data)) = x {
Some(data)
} else {
found_non_data_push = true;
None
})
.collect();
if found_non_data_push {
None
} else {
Some(PegoutData {
value,
asset: self.asset,
genesis_hash,
script_pubkey,
extra_data: remainder,
})
}
}
/// Whether or not this output is a fee output
pub fn is_fee(&self) -> bool {
self.script_pubkey.is_empty() && self.value.is_explicit() && self.asset.is_explicit()
}
/// Extracts the minimum value from the rangeproof, if there is one, or returns 0.
pub fn minimum_value(&self) -> u64 {
let min_value = u64::from(self.script_pubkey.is_op_return());
match self.value {
confidential::Value::Null => min_value,
confidential::Value::Explicit(n) => n,
confidential::Value::Confidential(..) => {
match &self.witness.rangeproof {
None => min_value,
Some(prf) => {
// inefficient, consider implementing index on rangeproof
let prf = prf.serialize();
debug_assert!(prf.len() > 10);
let has_nonzero_range = prf[0] & 64 == 64;
let has_min = prf[0] & 32 == 32;
if !has_min {
min_value
} else if has_nonzero_range {
bitcoin::consensus::deserialize::<u64>(&prf[2..10])
.expect("any 8 bytes is a u64")
.swap_bytes() // min-value is BE
} else {
bitcoin::consensus::deserialize::<u64>(&prf[1..9])
.expect("any 8 bytes is a u64")
.swap_bytes() // min-value is BE
}
}
}
}
}
}
/// Returns if at least some part of this output are blinded
pub fn is_partially_blinded(&self) -> bool {
self.asset.is_confidential() || self.value.is_confidential() || !self.witness.is_empty()
}
}
/// Elements transaction
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Transaction {
/// Transaction version field (should always be 2)
pub version: u32,
/// Transaction locktime
pub lock_time: LockTime,
/// Vector of inputs
pub input: Vec<TxIn>,
/// Vector of outputs
pub output: Vec<TxOut>,
}
serde_struct_impl!(Transaction, version, lock_time, input, output);
impl Transaction {
/// Whether the transaction is a coinbase tx
pub fn is_coinbase(&self) -> bool {
self.input.len() == 1 && self.input[0].is_coinbase()
}
/// Determines whether a transaction has any non-null witnesses
pub fn has_witness(&self) -> bool {
self.input.iter().any(|i| !i.witness.is_empty()) ||
self.output.iter().any(|o| !o.witness.is_empty())
}
/// Get the "weight" of this transaction; roughly equivalent to BIP141, in that witness data is
/// counted as 1 while non-witness data is counted as 4.
#[deprecated(since = "0.19.1", note = "Please use `Transaction::weight` instead.")]
pub fn get_weight(&self) -> usize {
self.weight()
}
/// Get the "weight" of this transaction; roughly equivalent to BIP141, in that witness data is
/// counted as 1 while non-witness data is counted as 4.
pub fn weight(&self) -> usize {
self.scaled_size(4)
}
/// Gets the regular byte-wise consensus-serialized size of this transaction.
#[deprecated(since = "0.19.1", note = "Please use `Transaction::size` instead.")]
pub fn get_size(&self) -> usize {
self.size()
}
/// Gets the regular byte-wise consensus-serialized size of this transaction.
pub fn size(&self) -> usize {
self.scaled_size(1)
}
/// Returns the "virtual size" (vsize) of this transaction.
///
/// Will be `ceil(weight / 4.0)`.
#[inline]
pub fn vsize(&self) -> usize {
let weight = self.weight();
(weight + 4 - 1) / 4
}
/// Get the "discount weight" of this transaction; this is the weight minus the output witnesses and minus the
/// differences between asset and nonce commitments from their explicit values (weighted as part of the base transaction).
pub fn discount_weight(&self) -> usize {
let mut weight = self.scaled_size(4);
for out in &self.output {
let rp_len = out.witness.rangeproof_len();
let sp_len = out.witness.surjectionproof_len();
let witness_weight = VarInt(sp_len as u64).size() + sp_len + VarInt(rp_len as u64).size() + rp_len;
weight -= witness_weight.saturating_sub(2); // explicit transactions have 1 byte for each empty proof
if out.value.is_confidential() {
weight -= (33 - 9) * 4;
}
if out.nonce.is_confidential() {
weight -= (33 - 1) * 4;
}
}
weight
}
/// Returns the "discount virtual size" (discountvsize) of this transaction.
///
/// Will be `ceil(discount weight / 4.0)`.
pub fn discount_vsize(&self) -> usize {
(self.discount_weight() + 4 - 1) / 4
}
fn scaled_size(&self, scale_factor: usize) -> usize {
let witness_flag = self.has_witness();
let input_weight = self.input.iter().map(|input| {
scale_factor * (
32 + 4 + 4 + // output + nSequence
VarInt(input.script_sig.len() as u64).size() +
input.script_sig.len() + if input.has_issuance() {
64 +
input.asset_issuance.amount.encoded_length() +
input.asset_issuance.inflation_keys.encoded_length()
} else {
0
}
) + if witness_flag {
let amt_prf_len = input.witness.amount_rangeproof.as_ref()
.map_or(0, |x| x.len());
let keys_prf_len = input.witness.inflation_keys_rangeproof.as_ref()
.map_or(0, |x| x.len());
VarInt(amt_prf_len as u64).size() +
amt_prf_len +
VarInt(keys_prf_len as u64).size() +
keys_prf_len +
VarInt(input.witness.script_witness.len() as u64).size() +
input.witness.script_witness.iter().map(|wit|
VarInt(wit.len() as u64).size() +
wit.len()
).sum::<usize>() +
VarInt(input.witness.pegin_witness.len() as u64).size() +
input.witness.pegin_witness.iter().map(|wit|
VarInt(wit.len() as u64).size() +
wit.len()
).sum::<usize>()
} else {
0
}
}).sum::<usize>();
let output_weight = self.output.iter().map(|output| {