-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathtransaction.rs
2612 lines (2404 loc) · 114 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
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 crate::{
confidential::{
AssetBlindingFactor, AssetCommitment, Nonce, ValueBlindingFactor, ValueCommitment,
},
encode::{self, Decodable, Encodable, Error},
issuance::AssetId,
opcodes,
script::Instruction,
Script, Txid, Wtxid,
};
use bitcoin::{self, hashes::Hash, VarInt};
use std::{collections::HashMap, fmt, io};
/// Elements transaction
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize),
serde(crate = "serde_crate")
)]
pub struct Transaction {
/// Transaction version field (should always be 2)
pub version: u32,
/// Transaction locktime
pub lock_time: u32,
/// Vector of inputs
pub input: Vec<TxIn>,
/// Vector of outputs
pub output: Vec<TxOut>,
}
/// A transaction input, which defines old coins to be consumed
#[derive(Clone, PartialEq, Eq, Debug, Hash)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize),
serde(crate = "serde_crate")
)]
pub struct TxIn {
/// The reference to the previous output that is being used an an input
pub previous_output: OutPoint,
/// Flag indicating that `previous_outpoint` refers to something on the main chain
pub is_pegin: bool,
/// Flag indicating that `previous_outpoint` has an asset issuance attached
pub has_issuance: 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: u32,
/// 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,
}
/// Transaction output
#[derive(Clone, PartialEq, Eq, Debug, Hash)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize),
serde(crate = "serde_crate")
)]
pub enum TxOut {
Explicit(ExplicitTxOut),
Confidential(ConfidentialTxOut),
Null(NullTxOut),
}
/// A reference to a transaction output
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize),
serde(crate = "serde_crate")
)]
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,
}
impl OutPoint {
/// Create a new outpoint.
pub fn new(txid: Txid, vout: u32) -> OutPoint {
OutPoint { txid, vout }
}
}
/// Description of an asset issuance in a transaction input
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize),
serde(crate = "serde_crate")
)]
pub enum AssetIssuance {
Explicit(ExplicitAssetIssuance),
Confidential(ConfidentialAssetIssuance),
Null(NullAssetIssuance),
}
/// Transaction input witness
#[derive(Clone, Default, PartialEq, Eq, Debug, Hash)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize),
serde(crate = "serde_crate")
)]
pub struct TxInWitness {
/// Amount rangeproof
pub amount_rangeproof: Vec<u8>,
/// Rangeproof for inflation keys
pub inflation_keys_rangeproof: Vec<u8>,
/// Traditional script witness
pub script_witness: Vec<Vec<u8>>,
/// Pegin witness, basically the same thing
pub pegin_witness: Vec<Vec<u8>>,
}
#[derive(Clone, PartialEq, Eq, Debug, Hash)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize),
serde(crate = "serde_crate")
)]
pub struct ExplicitTxOut {
/// Committed asset
pub asset: ExplicitAsset,
/// Committed amount
pub value: ExplicitValue,
/// Scriptpubkey
pub script_pubkey: Script,
/// There should be no such thing as a nonce for an explicit
/// output, but Elements will deserialize such a thing and even
/// produce it.
pub nonce: Option<Nonce>,
}
/// Transaction output
#[derive(Clone, PartialEq, Eq, Debug, Hash)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize),
serde(crate = "serde_crate")
)]
pub struct ConfidentialTxOut {
/// Committed asset
pub asset: AssetCommitment,
/// Committed amount
pub value: ValueCommitment,
/// Nonce (ECDH key passed to recipient)
///
/// TODO: I think this is only `None` if we spend an asset issuance.
pub nonce: Option<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,
}
#[derive(Clone, PartialEq, Eq, Debug, Hash)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize),
serde(crate = "serde_crate")
)]
pub struct NullTxOut {
pub script_pubkey: Script,
}
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize),
serde(crate = "serde_crate")
)]
pub struct ExplicitAssetIssuance {
/// Zero for a new asset issuance; otherwise a blinding factor for the input
pub asset_blinding_nonce: [u8; 32],
/// Freeform entropy field
pub asset_entropy: [u8; 32],
/// Amount of asset to issue
pub amount: ExplicitValue,
/// Amount of inflation keys to issue
pub inflation_keys: ExplicitValue,
}
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize),
serde(crate = "serde_crate")
)]
pub struct ConfidentialAssetIssuance {
/// Zero for a new asset issuance; otherwise a blinding factor for the input
pub asset_blinding_nonce: [u8; 32],
/// Freeform entropy field
pub asset_entropy: [u8; 32],
/// Amount of asset to issue
pub amount: ValueCommitment,
/// Amount of inflation keys to issue
pub inflation_keys: Option<ValueCommitment>,
}
#[derive(Copy, Clone, Default, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize),
serde(crate = "serde_crate")
)]
pub struct NullAssetIssuance {
/// Zero for a new asset issuance; otherwise a blinding factor for the input
pub asset_blinding_nonce: [u8; 32],
/// Freeform entropy field
pub asset_entropy: [u8; 32],
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash, PartialOrd, Ord)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize),
serde(crate = "serde_crate", transparent)
)]
pub struct ExplicitAsset(pub AssetId);
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash, PartialOrd, Ord)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize),
serde(crate = "serde_crate", transparent)
)]
pub struct ExplicitValue(pub u64);
/// Transaction output witness
#[derive(Clone, Default, PartialEq, Eq, Debug, Hash)]
#[cfg_attr(
feature = "serde",
derive(serde::Serialize, serde::Deserialize),
serde(crate = "serde_crate")
)]
pub struct TxOutWitness {
/// Surjection proof showing that the asset commitment is legitimate
pub surjection_proof: Vec<u8>,
/// Rangeproof showing that the value commitment is legitimate
pub rangeproof: Vec<u8>,
}
/// 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 auxillary
/// 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,
}
/// 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: ExplicitAsset,
/// Genesis hash of the target blockchain
pub genesis_hash: bitcoin::BlockHash,
/// Scriptpubkey to create on the target blockchain
pub script_pubkey: Script,
/// Remaining pegout data used by some forks of Elements
pub extra_data: Vec<&'txo [u8]>,
}
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.has_witness())
}
/// 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 get_weight(&self) -> usize {
self.get_scaled_size(4)
}
/// Gets the regular byte-wise consensus-serialized size of this transaction.
pub fn get_size(&self) -> usize {
self.get_scaled_size(1)
}
fn get_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).len() as usize +
input.script_sig.len() + if input.has_issuance() {
input.asset_issuance.encoded_length()
} else {
0
}) + if witness_flag {
input.witness.encoded_length()
} else {
0
}
})
.sum::<usize>();
let output_weight = self
.output
.iter()
.map(|output| {
scale_factor * output.encoded_length()
+ if witness_flag {
output.witness_length()
} else {
0
}
})
.sum::<usize>();
scale_factor
* (
4 + // version
4 + // locktime
VarInt(self.input.len() as u64).len() as usize +
VarInt(self.output.len() as u64).len() as usize +
1
// segwit flag byte (note this is *not* witness data in Elements)
)
+ input_weight
+ output_weight
}
/// The txid of the transaction.
pub fn txid(&self) -> Txid {
let mut enc = bitcoin::Txid::engine();
self.version.consensus_encode(&mut enc).unwrap();
0u8.consensus_encode(&mut enc).unwrap();
self.input.consensus_encode(&mut enc).unwrap();
self.output.consensus_encode(&mut enc).unwrap();
self.lock_time.consensus_encode(&mut enc).unwrap();
Txid::from_engine(enc)
}
/// Get the witness txid of the transaction.
pub fn wtxid(&self) -> Wtxid {
let mut enc = Txid::engine();
self.consensus_encode(&mut enc).unwrap();
Wtxid::from_engine(enc)
}
/// Get the total transaction fee in the given asset.
pub fn fee_in(&self, asset: AssetId) -> u64 {
// is_fee checks for explicit asset and value, so we can unwrap them here.
self.output
.iter()
.filter(|o| o.is_fee())
.filter_map(|o| o.as_explicit())
.filter(|e| e.asset.0 == asset)
.map(|o| o.value.0)
.sum()
}
/// Get all fees in all assets.
pub fn all_fees(&self) -> HashMap<AssetId, u64> {
let mut fees = HashMap::new();
for out in self
.output
.iter()
.filter(|o| o.is_fee())
.filter_map(|o| o.as_explicit())
{
// is_fee checks for explicit asset and value, so we can unwrap them here.
let asset = out.asset.0;
let entry = fees.entry(asset).or_insert(0);
*entry += out.value.0;
}
fees
}
}
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
}
/// 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> {
if !self.is_pegin {
return None;
}
if self.witness.pegin_witness.len() != 6 {
return None;
}
macro_rules! opt_try (
($res:expr) => { match $res { Ok(x) => x, Err(_) => return None } }
);
Some(PeginData {
// Cast of an elements::OutPoint to a bitcoin::OutPoint
outpoint: bitcoin::OutPoint {
txid: bitcoin::Txid::from(self.previous_output.txid.as_hash()),
vout: self.previous_output.vout,
},
value: opt_try!(bitcoin::consensus::deserialize(
&self.witness.pegin_witness[0]
)),
asset: opt_try!(encode::deserialize(&self.witness.pegin_witness[1])),
genesis_hash: opt_try!(bitcoin::consensus::deserialize(
&self.witness.pegin_witness[2]
)),
claim_script: &self.witness.pegin_witness[3],
tx: &self.witness.pegin_witness[4],
merkle_proof: &self.witness.pegin_witness[5],
referenced_block: bitcoin::BlockHash::hash(&self.witness.pegin_witness[5][0..80]),
})
}
/// Helper to determine whether an input has an asset issuance attached
pub fn has_issuance(&self) -> bool {
self.has_issuance
}
}
#[derive(Debug)]
pub struct NoBlindingKeyInAddress;
impl fmt::Display for NoBlindingKeyInAddress {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "the address is missing a blinding key")
}
}
impl std::error::Error for NoBlindingKeyInAddress {}
impl TxOut {
/// Creates a new confidential output that is **not** the last one in the transaction.
#[cfg(feature = "wally-sys")]
pub fn new_not_last_confidential<R, C>(
rng: &mut R,
secp: &bitcoin::secp256k1::Secp256k1<C>,
value: u64,
address: crate::Address,
asset: AssetId,
inputs: &[(
AssetId,
u64,
AssetCommitment,
AssetBlindingFactor,
ValueBlindingFactor,
)],
) -> Result<(Self, AssetBlindingFactor, ValueBlindingFactor), NoBlindingKeyInAddress>
where
R: bitcoin::secp256k1::rand::RngCore + bitcoin::secp256k1::rand::CryptoRng,
C: bitcoin::secp256k1::Signing,
{
let out_abf = AssetBlindingFactor::new(rng);
let out_asset = AssetCommitment::new(asset, out_abf);
let out_vbf = ValueBlindingFactor::random(rng);
let value_commitment = ValueCommitment::new(value, out_asset, out_vbf);
let (nonce, sender_ephemeral_sk) = Nonce::new(rng, secp);
let range_proof = crate::wally::asset_rangeproof(
value,
address
.blinding_pubkey
.ok_or_else(|| NoBlindingKeyInAddress)?,
sender_ephemeral_sk,
asset,
out_abf,
out_vbf,
value_commitment,
&address.script_pubkey(),
out_asset,
1,
0,
52,
);
let inputs = inputs
.iter()
.copied()
.map(|(id, _, asset, abf, _)| (id, abf, asset))
.collect::<Vec<_>>();
let surjection_proof =
crate::wally::asset_surjectionproof(rng, asset, out_abf, out_asset, &inputs);
let txout = TxOut::Confidential(ConfidentialTxOut {
asset: out_asset,
value: value_commitment,
nonce: Some(nonce),
script_pubkey: address.script_pubkey(),
witness: TxOutWitness {
surjection_proof,
rangeproof: range_proof,
},
});
Ok((txout, out_abf, out_vbf))
}
/// Creates a new confidential output that IS the last one in the transaction.
#[cfg(feature = "wally-sys")]
pub fn new_last_confidential<R, C>(
rng: &mut R,
secp: &bitcoin::secp256k1::Secp256k1<C>,
value: u64,
address: crate::Address,
asset: AssetId,
inputs: &[(
AssetId,
u64,
AssetCommitment,
AssetBlindingFactor,
ValueBlindingFactor,
)],
outputs: &[(u64, AssetBlindingFactor, ValueBlindingFactor)],
) -> Result<Self, NoBlindingKeyInAddress>
where
R: bitcoin::secp256k1::rand::RngCore + bitcoin::secp256k1::rand::CryptoRng,
C: bitcoin::secp256k1::Signing,
{
let (surjection_proof_inputs, value_blind_inputs) = inputs
.iter()
.copied()
.map(|(id, value, asset, abf, vbf)| ((id, abf, asset), (value, abf, vbf)))
.unzip::<_, _, Vec<_>, Vec<_>>();
let out_abf = AssetBlindingFactor::new(rng);
let out_asset = AssetCommitment::new(asset, out_abf);
let out_vbf = ValueBlindingFactor::last(value, out_abf, &value_blind_inputs, &outputs);
let value_commitment = ValueCommitment::new(value, out_asset, out_vbf);
let (nonce, sender_ephemeral_sk) = Nonce::new(rng, secp);
let range_proof = crate::wally::asset_rangeproof(
value,
address
.blinding_pubkey
.ok_or_else(|| NoBlindingKeyInAddress)?,
sender_ephemeral_sk,
asset,
out_abf,
out_vbf,
value_commitment,
&address.script_pubkey(),
out_asset,
1,
0,
52,
);
let surjection_proof = crate::wally::asset_surjectionproof(
rng,
asset,
out_abf,
out_asset,
&surjection_proof_inputs,
);
let txout = TxOut::Confidential(ConfidentialTxOut {
asset: out_asset,
value: value_commitment,
nonce: Some(nonce),
script_pubkey: address.script_pubkey(),
witness: TxOutWitness {
surjection_proof,
rangeproof: range_proof,
},
});
Ok(txout)
}
pub fn new_explicit(asset: AssetId, value: u64, script_pubkey: Script) -> Self {
TxOut::Explicit(ExplicitTxOut {
asset: ExplicitAsset(asset),
value: ExplicitValue(value),
script_pubkey,
nonce: None,
})
}
pub fn new_fee(asset: AssetId, value: u64) -> Self {
TxOut::new_explicit(asset, value, Script::default())
}
pub fn script_pubkey(&self) -> &Script {
match self {
Self::Null(inner) => &inner.script_pubkey,
Self::Confidential(inner) => &inner.script_pubkey,
Self::Explicit(inner) => &inner.script_pubkey,
}
}
pub fn as_explicit(&self) -> Option<&ExplicitTxOut> {
match self {
Self::Explicit(explicit) => Some(&explicit),
_ => None,
}
}
pub fn into_explicit(self) -> Option<ExplicitTxOut> {
match self {
Self::Explicit(explicit) => Some(explicit),
_ => None,
}
}
pub fn as_confidential(&self) -> Option<&ConfidentialTxOut> {
match self {
Self::Confidential(confidential) => Some(&confidential),
_ => None,
}
}
pub fn into_confidential(self) -> Option<ConfidentialTxOut> {
match self {
Self::Confidential(confidential) => Some(confidential),
_ => None,
}
}
pub fn has_witness(&self) -> bool {
match self {
Self::Confidential(confidential) => !confidential.witness.is_empty(),
_ => false,
}
}
pub fn encoded_length(&self) -> usize {
match self {
Self::Confidential(inner) => inner.encoded_length(),
Self::Explicit(inner) => inner.encoded_length(),
Self::Null(inner) => inner.encoded_length(),
}
}
pub fn witness_length(&self) -> usize {
match self {
Self::Confidential(ConfidentialTxOut { witness, .. }) => witness.encoded_length(),
_ => TxOutWitness::default().encoded_length(),
}
}
/// 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> {
let txout = match self {
Self::Explicit(txout) => Some(txout),
_ => None,
}?;
// Must be NULLDATA
if !self.is_null_data() {
return None;
}
let value = txout.value;
let mut iter = self.script_pubkey().instructions();
iter.next(); // Skip OP_RETURN
// Parse destination chain's genesis block
let genesis_hash = if let Some(Ok(Instruction::PushBytes(data))) = iter.next() {
if let Ok(hash) = bitcoin::BlockHash::from_slice(data) {
hash
} else {
return None;
}
} else {
return None;
};
// Parse destination scriptpubkey
let script_pubkey = if let Some(Ok(Instruction::PushBytes(data))) = iter.next() {
if data.is_empty() {
return None;
} else {
Script::from(data.to_owned())
}
} else {
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 {
asset: txout.asset,
value: value.0,
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() && matches!(self, Self::Explicit(_))
}
/// Extracts the minimum value from the rangeproof, if there is one, or returns 0.
pub fn minimum_value(&self) -> u64 {
let min_value = if self.script_pubkey().is_op_return() {
0
} else {
1
};
match self {
Self::Null { .. } => min_value,
Self::Explicit(explicit) => explicit.value.0,
Self::Confidential(ConfidentialTxOut { witness, .. }) => {
if witness.rangeproof.is_empty() {
min_value
} else {
debug_assert!(witness.rangeproof.len() > 10);
let has_nonzero_range = witness.rangeproof[0] & 64 == 64;
let has_min = witness.rangeproof[0] & 32 == 32;
if !has_min {
min_value
} else if has_nonzero_range {
bitcoin::consensus::deserialize::<u64>(&witness.rangeproof[2..10])
.expect("any 8 bytes is a u64")
.swap_bytes() // min-value is BE
} else {
bitcoin::consensus::deserialize::<u64>(&witness.rangeproof[1..9])
.expect("any 8 bytes is a u64")
.swap_bytes() // min-value is BE
}
}
}
}
}
}
impl AssetIssuance {
pub fn encoded_length(&self) -> usize {
match self {
AssetIssuance::Null(inner) => inner.encoded_length(),
AssetIssuance::Explicit(inner) => inner.encoded_length(),
AssetIssuance::Confidential(inner) => inner.encoded_length(),
}
}
}
impl ExplicitAssetIssuance {
pub fn encoded_length(&self) -> usize {
32 + 32 + self.amount.encoded_length() + self.inflation_keys.encoded_length()
}
}
impl ConfidentialAssetIssuance {
pub fn encoded_length(&self) -> usize {
32 + 32
+ self.amount.encoded_length()
+ match self.inflation_keys {
Some(keys) => keys.encoded_length(),
None => 1,
}
}
}
impl NullAssetIssuance {
pub fn encoded_length(&self) -> usize {
32 + 32 + 1 + 1
}
}
impl TxInWitness {
/// Whether this witness is null
pub fn is_empty(&self) -> bool {
self.amount_rangeproof.is_empty()
&& self.inflation_keys_rangeproof.is_empty()
&& self.script_witness.is_empty()
&& self.pegin_witness.is_empty()
}
pub fn encoded_length(&self) -> usize {
let amount_rp_len = self.amount_rangeproof.len();
let inflation_keys_rp_len = self.inflation_keys_rangeproof.len();
let script_w = &self.script_witness;
let pegin_w = &self.pegin_witness;
let amount_enc_length = VarInt(amount_rp_len as u64).len() as usize + amount_rp_len;
let inflation_keys_enc_length =
VarInt(inflation_keys_rp_len as u64).len() as usize + inflation_keys_rp_len;
let script_w_enc_length = VarInt(script_w.len() as u64).len() as usize
+ script_w
.iter()
.map(|wit| VarInt(wit.len() as u64).len() as usize + wit.len())
.sum::<usize>();
let pegin_w_enc_length = VarInt(pegin_w.len() as u64).len() as usize
+ pegin_w
.iter()
.map(|wit| VarInt(wit.len() as u64).len() as usize + wit.len())
.sum::<usize>();
amount_enc_length + inflation_keys_enc_length + script_w_enc_length + pegin_w_enc_length
}
}
impl Default for AssetIssuance {
fn default() -> Self {
Self::Null(NullAssetIssuance::default())
}
}
impl Encodable for ExplicitAssetIssuance {
fn consensus_encode<S: io::Write>(&self, mut s: S) -> Result<usize, encode::Error> {
Ok(self.asset_blinding_nonce.consensus_encode(&mut s)?
+ self.asset_entropy.consensus_encode(&mut s)?
+ self.amount.consensus_encode(&mut s)?
+ self.inflation_keys.consensus_encode(&mut s)?)
}
}
impl Encodable for ConfidentialAssetIssuance {
fn consensus_encode<S: io::Write>(&self, mut s: S) -> Result<usize, encode::Error> {
Ok(self.asset_blinding_nonce.consensus_encode(&mut s)?
+ self.asset_entropy.consensus_encode(&mut s)?
+ self.amount.consensus_encode(&mut s)?
+ match self.inflation_keys {
Some(keys) => keys.consensus_encode(&mut s)?,
None => 0u8.consensus_encode(&mut s)?,
})
}
}
impl Encodable for NullAssetIssuance {
fn consensus_encode<S: io::Write>(&self, mut s: S) -> Result<usize, encode::Error> {
Ok(self.asset_blinding_nonce.consensus_encode(&mut s)?
+ self.asset_entropy.consensus_encode(&mut s)?
+ 0u8.consensus_encode(&mut s)?
+ 0u8.consensus_encode(&mut s)?)
}
}
impl Encodable for AssetIssuance {
fn consensus_encode<S: io::Write>(&self, mut s: S) -> Result<usize, encode::Error> {
match self {
AssetIssuance::Confidential(inner) => inner.consensus_encode(&mut s),
AssetIssuance::Explicit(inner) => inner.consensus_encode(&mut s),
AssetIssuance::Null(inner) => inner.consensus_encode(&mut s),
}
}
}
impl Decodable for AssetIssuance {
fn consensus_decode<D: io::BufRead>(mut d: D) -> Result<Self, Error> {
let asset_blinding_nonce = Decodable::consensus_decode(&mut d)?;
let asset_entropy = Decodable::consensus_decode(&mut d)?;
let buffer = d.fill_buf()?;
if buffer.is_empty() {
return Err(Error::UnexpectedEOF);
}
Ok(match buffer[0] {
0 => {
let amount_tag = u8::consensus_decode(&mut d)?;
if amount_tag != 0 {
return Err(Error::InvalidTag {
expected: 0,
got: amount_tag,
});
}
let keys_tag = u8::consensus_decode(&mut d)?;
if keys_tag != 0 {
return Err(Error::InvalidTag {
expected: 0,
got: keys_tag,
});
}
AssetIssuance::Null(NullAssetIssuance {
asset_blinding_nonce,
asset_entropy,
})
}
1 => AssetIssuance::Explicit(ExplicitAssetIssuance {
asset_blinding_nonce,
asset_entropy,