-
Notifications
You must be signed in to change notification settings - Fork 109
/
Copy pathtransaction.rs
3253 lines (2917 loc) · 176 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
use crate::address::ZcashAddress;
use crate::amount::ZcashAmount;
use crate::extended_private_key::ZcashExtendedPrivateKey;
use crate::format::ZcashFormat;
use crate::librustzcash::zip32::prf_expand;
use crate::network::ZcashNetwork;
use crate::private_key::{SaplingOutgoingViewingKey, ZcashPrivateKey};
use crate::public_key::ZcashPublicKey;
use wagyu_model::{ExtendedPrivateKey, PrivateKey, Transaction, TransactionError, TransactionId};
use base58::FromBase58;
use blake2b_simd::{Hash, Params, State};
use rand::{rngs::StdRng, Rng};
use rand_core::SeedableRng;
use secp256k1;
use serde::Serialize;
use sha2::{Digest, Sha256};
use std::{fmt, io::{self, BufReader, Read}, str::FromStr};
// librustzcash crates
use bellman::groth16::{prepare_verifying_key, Parameters, PreparedVerifyingKey, Proof};
use ff::{Field, PrimeField, PrimeFieldRepr};
use pairing::bls12_381::{Bls12, Fr, FrRepr};
use zcash_primitives::{
jubjub::{edwards, fs::Fs},
keys::{ExpandedSpendingKey, FullViewingKey, OutgoingViewingKey},
merkle_tree::MerklePath,
note_encryption::{try_sapling_note_decryption, Memo, SaplingNoteEncryption},
primitives::{Diversifier, Note, PaymentAddress},
redjubjub::{PrivateKey as jubjubPrivateKey, PublicKey as jubjubPublicKey, Signature as jubjubSignature},
sapling::{spend_sig, Node},
transaction::components::Amount,
JUBJUB,
};
use zcash_proofs::sapling::{SaplingProvingContext, SaplingVerificationContext};
const GROTH_PROOF_SIZE: usize = 48 + 96 + 48; // π_A + π_B + π_C
/// Returns the variable length integer of the given value.
/// https://en.bitcoin.it/wiki/Protocol_documentation#Variable_length_integer
pub fn variable_length_integer(value: u64) -> Result<Vec<u8>, TransactionError> {
match value {
// bounded by u8::max_value()
0..=252 => Ok(vec![value as u8]),
// bounded by u16::max_value()
253..=65535 => Ok([vec![0xfd], (value as u16).to_le_bytes().to_vec()].concat()),
// bounded by u32::max_value()
65536..=4294967295 => Ok([vec![0xfe], (value as u32).to_le_bytes().to_vec()].concat()),
// bounded by u64::max_value()
_ => Ok([vec![0xff], value.to_le_bytes().to_vec()].concat()),
}
}
/// Decode the value of a variable length integer.
/// https://en.bitcoin.it/wiki/Protocol_documentation#Variable_length_integer
pub fn read_variable_length_integer<R: Read>(mut reader: R) -> Result<usize, TransactionError> {
let mut flag = [0u8; 1];
reader.read(&mut flag)?;
match flag[0] {
0..=252 => Ok(flag[0] as usize),
0xfd => {
let mut size = [0u8; 2];
reader.read(&mut size)?;
match u16::from_le_bytes(size) {
s if s < 253 => return Err(TransactionError::InvalidVariableSizeInteger(s as usize)),
s => Ok(s as usize),
}
}
0xfe => {
let mut size = [0u8; 4];
reader.read(&mut size)?;
match u32::from_le_bytes(size) {
s if s < 65536 => return Err(TransactionError::InvalidVariableSizeInteger(s as usize)),
s => Ok(s as usize),
}
}
_ => {
let mut size = [0u8; 8];
reader.read(&mut size)?;
match u64::from_le_bytes(size) {
s if s < 4294967296 => return Err(TransactionError::InvalidVariableSizeInteger(s as usize)),
s => Ok(s as usize),
}
}
}
}
/// Abstraction over a reader which hashes the data being read.
pub struct HashReader<R: Read> {
reader: R,
hasher: State,
}
impl<R: Read> HashReader<R> {
/// Construct a new `HashReader` given an existing `reader` by value.
pub fn new(reader: R) -> Self {
HashReader {
reader,
hasher: State::new(),
}
}
/// Destroy this reader and return the hash of what was read.
pub fn into_hash(self) -> String {
let hash = self.hasher.finalize();
let mut s = String::new();
for c in hash.as_bytes().iter() {
s += &format!("{:02x}", c);
}
s
}
}
impl<R: Read> Read for HashReader<R> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let bytes = self.reader.read(buf)?;
if bytes > 0 {
self.hasher.update(&buf[0..bytes]);
}
Ok(bytes)
}
}
/// Initialize the sapling parameters and verifying keys
pub fn load_sapling_parameters() -> (
Parameters<Bls12>,
PreparedVerifyingKey<Bls12>,
Parameters<Bls12>,
PreparedVerifyingKey<Bls12>,
) {
// Loads Zcash Sapling parameters as buffers
let (spend, output) = wagyu_zcash_parameters::load_sapling_parameters();
let mut spend_fs = HashReader::new(BufReader::with_capacity(1024 * 1024, &spend[..]));
let mut output_fs =
HashReader::new(BufReader::with_capacity(1024 * 1024, &output[..]));
// Deserialize params
let spend_params = Parameters::<Bls12>::read(&mut spend_fs, false)
.expect("couldn't deserialize Sapling spend parameters file");
let output_params = Parameters::<Bls12>::read(&mut output_fs, false)
.expect("couldn't deserialize Sapling spend parameters file");
// There is extra stuff (the transcript) at the end of the parameter file which is
// used to verify the parameter validity, but we're not interested in that. We do
// want to read it, though, so that the BLAKE2b computed afterward is consistent
// with `b2sum` on the files.
let mut sink = io::sink();
io::copy(&mut spend_fs, &mut sink)
.expect("couldn't finish reading Sapling spend parameter file");
io::copy(&mut output_fs, &mut sink)
.expect("couldn't finish reading Sapling output parameter file");
if spend_fs.into_hash() != "8270785a1a0d0bc77196f000ee6d221c9c9894f55307bd9357c3f0105d31ca63991ab91324160d8f53e2bbd3c2633a6eb8bdf5205d822e7f3f73edac51b2b70c" {
panic!("Sapling spend parameter is not correct. please file a Github issue.");
}
if output_fs.into_hash() != "657e3d38dbb5cb5e7dd2970e8b03d69b4787dd907285b5a7f0790dcc8072f60bf593b32cc2d1c030e00ff5ae64bf84c5c3beb84ddc841d48264b4a171744d028" {
panic!("Sapling output parameter is not correct, please file a Github issue.");
}
// Prepare verifying keys
let spend_vk = prepare_verifying_key(&spend_params.vk);
let output_vk = prepare_verifying_key(&output_params.vk);
(spend_params, spend_vk, output_params, output_vk)
}
/// Initialize the sapling proving context
pub fn initialize_proving_context() -> SaplingProvingContext {
SaplingProvingContext::new()
}
/// Initialize the sapling verifying context
pub fn initialize_verifying_context() -> SaplingVerificationContext {
SaplingVerificationContext::new()
}
pub struct ZcashVector;
impl ZcashVector {
/// Read and output a vector with a variable length integer
pub fn read<R: Read, E, F>(mut reader: R, func: F) -> Result<Vec<E>, TransactionError>
where
F: Fn(&mut R) -> Result<E, TransactionError>,
{
let count = read_variable_length_integer(&mut reader)?;
(0..count).map(|_| func(&mut reader)).collect()
}
}
/// Generate the script_pub_key of a corresponding address
pub fn create_script_pub_key<N: ZcashNetwork>(address: &ZcashAddress<N>) -> Result<Vec<u8>, TransactionError> {
match address.format() {
ZcashFormat::P2PKH => {
let address_bytes = &address.to_string().from_base58()?;
let pub_key_hash = address_bytes[2..(address_bytes.len() - 4)].to_vec();
let mut script = vec![];
script.push(Opcode::OP_DUP as u8);
script.push(Opcode::OP_HASH160 as u8);
script.extend(variable_length_integer(pub_key_hash.len() as u64)?);
script.extend(pub_key_hash);
script.push(Opcode::OP_EQUALVERIFY as u8);
script.push(Opcode::OP_CHECKSIG as u8);
Ok(script)
}
_ => unreachable!(),
}
}
/// Return the transaction header given a version
fn fetch_header_and_version_group_id(version: &str) -> (u32, u32) {
match version {
"sapling" => (2147483652, 0x892F2085),
// Zcash currently only supports sapling transactions
_ => unimplemented!(),
}
}
/// Returns a Blake256 hash of a given personalization, message, and optional Zcash version
fn blake2_256_hash(personalization: &str, message: Vec<u8>, version: Option<&str>) -> Hash {
let personalization = match version {
Some("sapling") => [personalization.as_bytes(), &(0x76b809bb as u32).to_le_bytes()].concat(),
Some("overwinter") => [personalization.as_bytes(), &(0x5ba81b19 as u32).to_le_bytes()].concat(),
Some(_) => [personalization.as_bytes(), &(0x76b809bb as u32).to_le_bytes()].concat(),
None => personalization.as_bytes().to_vec(),
};
Params::new()
.hash_length(32)
.personal(&personalization)
.to_state()
.update(&message)
.finalize()
}
/// Represents the signature hash opcode
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[allow(non_camel_case_types)]
pub enum SignatureHash {
SIGHASH_ALL = 1,
SIGHASH_NONE = 2,
SIGHASH_SINGLE = 3,
SIGHASH_ANYONECANPAY = 128,
}
impl fmt::Display for SignatureHash {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
SignatureHash::SIGHASH_ALL => write!(f, "SIGHASH_ALL"),
SignatureHash::SIGHASH_NONE => write!(f, "SIGHASH_NONE"),
SignatureHash::SIGHASH_SINGLE => write!(f, "SIGHASH_SINGLE"),
SignatureHash::SIGHASH_ANYONECANPAY => write!(f, "SIGHASH_ANYONECANPAY"),
}
}
}
impl SignatureHash {
fn from_byte(byte: &u8) -> Self {
match byte {
1 => SignatureHash::SIGHASH_ALL,
2 => SignatureHash::SIGHASH_NONE,
3 => SignatureHash::SIGHASH_SINGLE,
128 => SignatureHash::SIGHASH_ANYONECANPAY,
_ => SignatureHash::SIGHASH_ALL,
}
}
}
/// Represents the commonly used script opcodes
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[allow(non_camel_case_types)]
pub enum Opcode {
OP_DUP = 0x76,
OP_HASH160 = 0xa9,
OP_CHECKSIG = 0xac,
OP_EQUAL = 0x87,
OP_EQUALVERIFY = 0x88,
}
impl fmt::Display for Opcode {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Opcode::OP_DUP => write!(f, "OP_DUP"),
Opcode::OP_HASH160 => write!(f, "OP_HASH160"),
Opcode::OP_CHECKSIG => write!(f, "OP_CHECKSIG"),
Opcode::OP_EQUAL => write!(f, "OP_EQUAL"),
Opcode::OP_EQUALVERIFY => write!(f, "OP_EQUALVERIFY"),
}
}
}
/// Represents a Zcash transparent transaction outpoint
#[derive(Debug, Clone)]
pub struct Outpoint<N: ZcashNetwork> {
/// Previous transaction id (using Zcash RPC's reversed hash order) - 32 bytes
pub reverse_transaction_id: Vec<u8>,
/// Index of the transaction being used - 4 bytes
pub index: u32,
/// Amount associated with the UTXO - used for segwit transaction signatures
pub amount: Option<ZcashAmount>,
/// Script public key asssociated with claiming this particular input UTXO
pub script_pub_key: Option<Vec<u8>>,
/// Optional redeem script - for segwit transactions
pub redeem_script: Option<Vec<u8>>,
/// Address of the outpoint
pub address: Option<ZcashAddress<N>>,
}
impl<N: ZcashNetwork> Outpoint<N> {
/// Returns a new Zcash transaction outpoint
pub fn new(
reverse_transaction_id: Vec<u8>,
index: u32,
address: Option<ZcashAddress<N>>,
amount: Option<ZcashAmount>,
redeem_script: Option<Vec<u8>>,
script_pub_key: Option<Vec<u8>>,
) -> Result<Self, TransactionError> {
let script_pub_key = match address.clone() {
Some(address) => {
let script_pub_key = script_pub_key.unwrap_or(create_script_pub_key::<N>(&address)?);
if &address.format() == &ZcashFormat::P2PKH
&& script_pub_key[0] != Opcode::OP_DUP as u8
&& script_pub_key[1] != Opcode::OP_HASH160 as u8
&& script_pub_key[script_pub_key.len() - 1] != Opcode::OP_CHECKSIG as u8
{
return Err(TransactionError::InvalidScriptPubKey("P2PKH".into()));
};
Some(script_pub_key)
}
None => None,
};
Ok(Self {
reverse_transaction_id,
index,
amount,
redeem_script,
script_pub_key,
address,
})
}
}
/// Represents a Zcash transaction transparent input
#[derive(Debug, Clone)]
pub struct ZcashTransparentInput<N: ZcashNetwork> {
/// Outpoint - transaction id and index - 36 bytes
pub outpoint: Outpoint<N>,
/// Tx-in script - Variable size
pub script: Vec<u8>,
/// Sequence number - 4 bytes (normally 0xFFFFFFFF, unless lock > 0)
/// Also used in replace-by-fee - BIP 125.
pub sequence: Vec<u8>,
/// SIGHASH Code - 4 Bytes (used in signing raw transaction only)
pub sighash_code: SignatureHash,
/// If true, the input has been signed
pub is_signed: bool,
}
impl<N: ZcashNetwork> ZcashTransparentInput<N> {
const DEFAULT_SEQUENCE: [u8; 4] = [0xff, 0xff, 0xff, 0xff];
/// Returns a new Zcash transparent input without the script.
pub fn new(
transaction_id: Vec<u8>,
index: u32,
address: Option<ZcashAddress<N>>,
amount: Option<ZcashAmount>,
redeem_script: Option<Vec<u8>>,
script_pub_key: Option<Vec<u8>>,
sequence: Option<Vec<u8>>,
sighash_code: SignatureHash,
) -> Result<Self, TransactionError> {
if transaction_id.len() != 32 {
return Err(TransactionError::InvalidTransactionId(transaction_id.len()));
}
// Reverse hash order - https://bitcoin.org/en/developer-reference#hash-byte-order
let mut reverse_transaction_id = transaction_id;
reverse_transaction_id.reverse();
let outpoint = Outpoint::<N>::new(
reverse_transaction_id,
index,
address,
amount,
redeem_script,
script_pub_key,
)?;
let sequence = sequence.unwrap_or(ZcashTransparentInput::<N>::DEFAULT_SEQUENCE.to_vec());
Ok(Self {
outpoint,
script: Vec::new(),
sequence,
sighash_code,
is_signed: false,
})
}
/// Read and output a Zcash transaction transparent input
pub fn read<R: Read>(mut reader: &mut R) -> Result<Self, TransactionError> {
let mut transaction_hash = [0u8; 32];
reader.read(&mut transaction_hash)?;
let mut vin = [0u8; 4];
reader.read(&mut vin)?;
let outpoint = Outpoint {
reverse_transaction_id: transaction_hash.to_vec(),
index: u32::from_le_bytes(vin),
amount: None,
script_pub_key: None,
redeem_script: None,
address: None,
};
let script: Vec<u8> = ZcashVector::read(&mut reader, |s| {
let mut byte = [0u8; 1];
s.read(&mut byte)?;
Ok(byte[0])
})?;
let mut sequence = [0u8; 4];
reader.read(&mut sequence)?;
let script_len = read_variable_length_integer(&script[..])?;
let sighash_code = SignatureHash::from_byte(&match script_len {
0 => 0x01,
length => script[length],
});
Ok(Self {
outpoint,
script: script.to_vec(),
sequence: sequence.to_vec(),
sighash_code,
is_signed: script.len() > 0,
})
}
/// Returns the serialized transparent input.
pub fn serialize(&self, raw: bool, hash_preimage: bool) -> Result<Vec<u8>, TransactionError> {
let mut input = vec![];
input.extend(&self.outpoint.reverse_transaction_id);
input.extend(&self.outpoint.index.to_le_bytes());
match (raw, self.script.len()) {
(true, _) => input.extend(vec![0x00]),
(false, 0) => {
let script_pub_key = match &self.outpoint.script_pub_key {
Some(script) => script,
None => return Err(TransactionError::MissingOutpointScriptPublicKey),
};
input.extend(variable_length_integer(script_pub_key.len() as u64)?);
input.extend(script_pub_key);
}
(false, _) => {
input.extend(variable_length_integer(self.script.len() as u64)?);
input.extend(&self.script);
}
};
match (hash_preimage, &self.outpoint.amount) {
(true, Some(amount)) => input.extend(&amount.0.to_le_bytes()),
(true, None) => return Err(TransactionError::MissingOutpointAmount),
(false, _) => {}
};
input.extend(&self.sequence);
Ok(input)
}
}
/// Represents a Zcash transaction transparent output
#[derive(Debug, Clone)]
pub struct ZcashTransparentOutput {
/// The amount (in zatoshi)
pub amount: ZcashAmount,
/// The public key script
pub script_pub_key: Vec<u8>,
}
impl ZcashTransparentOutput {
/// Returns a new Zcash transparent output.
pub fn new<N: ZcashNetwork>(address: &ZcashAddress<N>, amount: ZcashAmount) -> Result<Self, TransactionError> {
Ok(Self {
amount,
script_pub_key: create_script_pub_key::<N>(address)?,
})
}
/// Read and output a Zcash transaction output
pub fn read<R: Read>(mut reader: &mut R) -> Result<Self, TransactionError> {
let mut amount = [0u8; 8];
reader.read(&mut amount)?;
let script_pub_key: Vec<u8> = ZcashVector::read(&mut reader, |s| {
let mut byte = [0u8; 1];
s.read(&mut byte)?;
Ok(byte[0])
})?;
Ok(Self {
amount: ZcashAmount::from_zatoshi(u64::from_le_bytes(amount) as i64)?,
script_pub_key,
})
}
/// Returns the serialized transparent output.
pub fn serialize(&self) -> Result<Vec<u8>, TransactionError> {
let mut output = vec![];
output.extend(&self.amount.0.to_le_bytes());
output.extend(variable_length_integer(self.script_pub_key.len() as u64)?);
output.extend(&self.script_pub_key);
Ok(output)
}
}
/// Represents a Zcash Sapling spend description
#[derive(Debug, Clone)]
pub struct SaplingSpendDescription {
/// The value commitment to the value of the input note, LEBS2OSP_256(repr_J(cv)).
pub cv: [u8; 32],
/// The root of the Sapling note commitment tree at a past block height, LEBS2OSP_256(rt).
pub anchor: [u8; 32],
/// The nullifier of the input note, LEBS2OSP_256(nf).
pub nullifier: [u8; 32],
/// The randomized public key for `spend_auth_sig`, LEBS2OSP_256(repr_J(rk)).
pub rk: [u8; 32],
/// The encoding of the zero knowledge proof used for the output circuit.
pub zk_proof: Vec<u8>,
/// The signature authorizing this spend.
pub spend_auth_sig: Option<Vec<u8>>,
}
impl SaplingSpendDescription {
/// Returns the serialized sapling spend description
pub fn serialize(&self, sighash: bool) -> Result<Vec<u8>, TransactionError> {
let mut input = vec![];
input.extend(&self.cv);
input.extend(&self.anchor);
input.extend(&self.nullifier);
input.extend(&self.rk);
input.extend(&self.zk_proof);
if let (Some(spend_auth_sig), false) = (&self.spend_auth_sig, sighash) {
input.extend(spend_auth_sig);
};
Ok(input)
}
/// Read and output a Zcash sapling spend description
pub fn read<R: Read>(reader: &mut R) -> Result<Self, TransactionError> {
let mut cv = [0u8; 32];
let mut anchor = [0u8; 32];
let mut nullifier = [0u8; 32];
let mut rk = [0u8; 32];
let mut zk_proof = [0u8; 192];
let mut spend_auth_sig = [0u8; 64];
reader.read(&mut cv)?;
reader.read(&mut anchor)?;
reader.read(&mut nullifier)?;
reader.read(&mut rk)?;
reader.read(&mut zk_proof)?;
reader.read(&mut spend_auth_sig)?;
Ok(Self {
cv,
anchor,
nullifier,
rk,
zk_proof: zk_proof.to_vec(),
spend_auth_sig: Some(spend_auth_sig.to_vec()),
})
}
}
/// Represents a Zcash transaction Shielded Spend parameters
#[derive(Debug, Clone)]
pub struct SaplingSpendParameters<N: ZcashNetwork> {
/// The Sapling extended secret key
pub extended_private_key: ZcashExtendedPrivateKey<N>,
/// The Sapling address diversifier
pub diversifier: [u8; 11],
/// The Sapling spend note
pub note: Note<Bls12>,
/// The alpha randomness
pub alpha: Fs,
/// The anchor
pub anchor: Fr,
/// The commitment witness
pub witness: MerklePath<Node>,
}
/// Represents a Zcash transaction Shielded Spend
#[derive(Debug, Clone)]
pub struct SaplingSpend<N: ZcashNetwork> {
/// The Sapling spend parameters
pub spend_parameters: Option<SaplingSpendParameters<N>>,
/// The spend description
pub spend_description: Option<SaplingSpendDescription>,
}
impl<N: ZcashNetwork> SaplingSpend<N> {
/// Returns a new Zcash sapling spend
pub fn new(
extended_private_key: &ZcashExtendedPrivateKey<N>,
cmu: &[u8; 32],
epk: &[u8; 32],
enc_ciphertext: &str,
anchor: Fr,
witness: MerklePath<Node>,
) -> Result<Self, TransactionError> {
let full_viewing_key = extended_private_key
.to_extended_public_key()
.to_extended_full_viewing_key()
.fvk
.to_bytes();
let ivk = FullViewingKey::<Bls12>::read(&full_viewing_key[..], &JUBJUB)?.vk.ivk();
let mut f = FrRepr::default();
f.read_le(&cmu[..])?;
let alpha = Fs::random(&mut StdRng::from_entropy());
let cmu = Fr::from_repr(f)?;
let enc_ciphertext_vec = hex::decode(enc_ciphertext)?;
let epk = match edwards::Point::<Bls12, _>::read(&epk[..], &JUBJUB)?.as_prime_order(&JUBJUB) {
Some(epk) => epk,
None => return Err(TransactionError::InvalidEphemeralKey(hex::encode(epk))),
};
let (note, payment_address, _memo) =
match try_sapling_note_decryption(&ivk.into(), &epk, &cmu, &enc_ciphertext_vec) {
None => return Err(TransactionError::FailedNoteDecryption(enc_ciphertext.into())),
Some((note, payment_address, memo)) => (note, payment_address, memo),
};
let spend_parameters = Some(SaplingSpendParameters {
extended_private_key: extended_private_key.clone(),
diversifier: payment_address.diversifier().0,
note,
alpha,
anchor,
witness,
});
Ok(Self {
spend_parameters,
spend_description: None,
})
}
/// Create Sapling spend description
pub fn create_sapling_spend_description(
&mut self,
proving_ctx: &mut SaplingProvingContext,
spend_params: &Parameters<Bls12>,
spend_vk: &PreparedVerifyingKey<Bls12>,
) -> Result<(), TransactionError> {
let spend_parameters = match &self.spend_parameters {
Some(spend_parameters) => spend_parameters,
None => return Err(TransactionError::MissingSpendParameters),
};
let spending_key = spend_parameters
.extended_private_key
.to_extended_spending_key()
.expsk
.to_bytes();
let proof_generation_key = ExpandedSpendingKey::<Bls12>::read(&spending_key[..])?.proof_generation_key(&JUBJUB);
let nf = &spend_parameters.note.nf(
&proof_generation_key.to_viewing_key(&JUBJUB),
spend_parameters.witness.position,
&JUBJUB,
);
let (proof, value_commitment, public_key) = proving_ctx.spend_proof(
proof_generation_key,
Diversifier(spend_parameters.diversifier),
spend_parameters.note.r,
spend_parameters.alpha,
spend_parameters.note.value,
spend_parameters.anchor,
spend_parameters.witness.clone(),
spend_params,
spend_vk,
&JUBJUB,
)?;
let mut cv = [0u8; 32];
let mut anchor = [0u8; 32];
let mut nullifier = [0u8; 32];
let mut rk = [0u8; 32];
let mut zk_proof = [0u8; GROTH_PROOF_SIZE];
value_commitment.write(&mut cv[..])?;
spend_parameters.anchor.into_repr().write_le(&mut anchor[..])?;
nullifier.copy_from_slice(nf);
public_key.write(&mut rk[..])?;
proof.write(&mut zk_proof[..])?;
let spend_description = SaplingSpendDescription {
cv,
anchor,
nullifier,
rk,
zk_proof: zk_proof.to_vec(),
spend_auth_sig: None,
};
self.spend_description = Some(spend_description);
Ok(())
}
/// Read and output a Zcash sapling spend
pub fn read<R: Read>(mut reader: &mut R) -> Result<Self, TransactionError> {
let spend_description = SaplingSpendDescription::read(&mut reader)?;
Ok(Self {
spend_parameters: None,
spend_description: Some(spend_description),
})
}
}
/// Represents a Zcash Sapling output description
#[derive(Debug, Clone)]
pub struct SaplingOutputDescription {
/// The value commitment to the value of the output note, LEBS2OSP_256(repr_J(cv)).
pub cv: [u8; 32],
/// The u-coordinate of the note commitment for the output note,
/// LEBS2OSP_256(cm_u) where cm_u = Extract_J^(r) (cm).
pub cmu: [u8; 32],
/// The encoding of an ephemeral Jubjub public key, LEBS2OSP_256(repr_J(epk)).
pub ephemeral_key: [u8; 32],
/// The ciphertext component for the encrypted output note, C_enc.
pub enc_ciphertext: Vec<u8>,
/// The ciphertext component for the encrypted output note, C_out.
pub out_ciphertext: Vec<u8>,
/// The encoding of the zero knowledge proof for the output circuit.
pub zk_proof: Vec<u8>,
}
impl SaplingOutputDescription {
/// Returns the serialized sapling output description
pub fn serialize(&self) -> Result<Vec<u8>, TransactionError> {
let mut output = vec![];
output.extend(&self.cv);
output.extend(&self.cmu);
output.extend(&self.ephemeral_key);
output.extend(&self.enc_ciphertext);
output.extend(&self.out_ciphertext);
output.extend(&self.zk_proof);
Ok(output)
}
/// Read and output a Zcash sapling spend description
pub fn read<R: Read>(reader: &mut R) -> Result<Self, TransactionError> {
let mut cv = [0u8; 32];
let mut cmu = [0u8; 32];
let mut ephemeral_key = [0u8; 32];
let mut enc_ciphertext = [0u8; 580];
let mut out_ciphertext = [0u8; 80];
let mut zk_proof = [0u8; 192];
reader.read(&mut cv)?;
reader.read(&mut cmu)?;
reader.read(&mut ephemeral_key)?;
reader.read(&mut enc_ciphertext)?;
reader.read(&mut out_ciphertext)?;
reader.read(&mut zk_proof)?;
Ok(Self {
cv,
cmu,
ephemeral_key,
enc_ciphertext: enc_ciphertext.to_vec(),
out_ciphertext: out_ciphertext.to_vec(),
zk_proof: zk_proof.to_vec(),
})
}
}
/// Represents a Zcash transaction Shielded Output parameters
#[derive(Debug, Clone)]
pub struct SaplingOutputParameters<N: ZcashNetwork> {
/// The Sapling address
pub address: ZcashAddress<N>,
/// The outgoing view key
pub ovk: SaplingOutgoingViewingKey,
/// The Sapling output address
pub to: PaymentAddress<Bls12>,
/// The Sapling output note
pub note: Note<Bls12>,
/// An optional memo
pub memo: Memo,
}
/// Represents a Zcash Sapling output
#[derive(Debug, Clone)]
pub struct SaplingOutput<N: ZcashNetwork> {
/// The Sapling output parameters
pub output_parameters: Option<SaplingOutputParameters<N>>,
/// The output description
pub output_description: Option<SaplingOutputDescription>,
}
impl<N: ZcashNetwork> SaplingOutput<N> {
/// Returns a new Zcash sapling output
pub fn new(
ovk: SaplingOutgoingViewingKey,
address: &ZcashAddress<N>,
value: ZcashAmount,
) -> Result<Self, TransactionError> {
let diversifier = match address.to_diversifier() {
Some(d) => {
let mut diversifier = [0u8; 11];
diversifier.copy_from_slice(&hex::decode(d)?);
diversifier
}
None => return Err(TransactionError::MissingDiversifier),
};
let pk_d = edwards::Point::<Bls12, _>::read(&address.to_diversified_transmission_key()?[..], &JUBJUB)?
.as_prime_order(&JUBJUB);
match pk_d {
None => return Err(TransactionError::InvalidOutputAddress(address.to_string())),
Some(pk_d) => {
let to = match PaymentAddress::from_parts(Diversifier(diversifier), pk_d.clone()) {
Some(to) => to,
None => return Err(TransactionError::InvalidOutputAddress(address.to_string())),
};
let g_d = match to.g_d(&JUBJUB) {
Some(g_d) => g_d,
None => return Err(TransactionError::InvalidOutputAddress(address.to_string())),
};
let note = Note {
g_d,
pk_d,
value: value.0 as u64,
r: Fs::random(&mut StdRng::from_entropy()),
};
let output_parameters = Some(SaplingOutputParameters {
address: address.clone(),
ovk,
to,
note,
memo: Memo::default(),
});
Ok(Self {
output_parameters,
output_description: None,
})
}
}
}
/// Create Sapling Output Description
pub fn create_sapling_output_description(
&mut self,
proving_ctx: &mut SaplingProvingContext,
verifying_ctx: &mut SaplingVerificationContext,
output_params: &Parameters<Bls12>,
output_vk: &PreparedVerifyingKey<Bls12>,
) -> Result<(), TransactionError> {
let output_parameters = match &self.output_parameters {
Some(output_parameters) => output_parameters,
None => return Err(TransactionError::MissingOutputParameters),
};
let ovk = OutgoingViewingKey(output_parameters.ovk.0);
let note_encryption = SaplingNoteEncryption::new(
ovk,
output_parameters.note.clone(),
output_parameters.to.clone(),
output_parameters.memo.clone(),
&mut StdRng::from_entropy(),
);
let (proof, value_commitment) = proving_ctx.output_proof(
note_encryption.esk().clone(),
output_parameters.to.clone(),
output_parameters.note.r,
output_parameters.note.value,
&output_params,
&JUBJUB,
);
// Generate the ciphertexts
let cm = output_parameters.note.cm(&JUBJUB);
let enc_ciphertext = note_encryption.encrypt_note_plaintext();
let out_ciphertext = note_encryption.encrypt_outgoing_plaintext(&value_commitment, &cm);
// Write the points as bytes
let mut cmu = [0u8; 32];
cmu.copy_from_slice(
&cm.into_repr()
.0
.iter()
.flat_map(|num| num.to_le_bytes().to_vec())
.collect::<Vec<u8>>(),
);
let mut cv = [0u8; 32]; // Value commitment
let mut ephemeral_key = [0u8; 32]; // EPK
let mut zk_proof = [0u8; GROTH_PROOF_SIZE];
value_commitment.write(&mut cv[..])?;
note_encryption.epk().write(&mut ephemeral_key[..])?;
proof.write(&mut zk_proof[..])?;
// Verify the output description
// Consider removing spend checks because zcash nodes also do this check when broadcasting transactions
match verifying_ctx.check_output(
value_commitment,
cm,
note_encryption.epk().clone().into(),
proof,
output_vk,
&JUBJUB,
) {
true => {}
false => {
return Err(TransactionError::InvalidOutputDescription(
output_parameters.address.to_string(),
))
}
};
let output_description = SaplingOutputDescription {
cv,
cmu,
ephemeral_key,
enc_ciphertext: enc_ciphertext.to_vec(),
out_ciphertext: out_ciphertext.to_vec(),
zk_proof: zk_proof.to_vec(),
};
self.output_description = Some(output_description);
Ok(())
}
/// Read and output a Zcash sapling output
pub fn read<R: Read>(mut reader: &mut R) -> Result<Self, TransactionError> {
let output_description = SaplingOutputDescription::read(&mut reader)?;
Ok(Self {
output_parameters: None,
output_description: Some(output_description),
})
}
}
/// Represents the Zcash transaction parameters
#[derive(Debug, Clone)]
pub struct ZcashTransactionParameters<N: ZcashNetwork> {
/// The header of the transaction (Overwintered flag and transaction version) (04000080 for Sapling)
pub header: u32,
/// The version group ID (0x892F2085 for Sapling)
pub version_group_id: u32,
/// The inputs for a transparent transaction, encoded as in Bitcoin.
pub transparent_inputs: Vec<ZcashTransparentInput<N>>,
/// The outputs for a transparent transaction, encoded as in Bitcoin,
pub transparent_outputs: Vec<ZcashTransparentOutput>,
/// The Unix epoch time (UTC) or block height, encoded as in Bitcoin. (4 bytes)
pub lock_time: u32,
/// The block height in the range {1 .. 499999999} after which the transaction will expire,
/// or 0 to disable expiry (ZIP-203).
pub expiry_height: u32,
/// The inputs for a shielded transaction, encoded as a sequence of Zcash spend descriptions.
pub shielded_inputs: Vec<SaplingSpend<N>>,
/// The outputs for a shielded transaction, encoded as a sequence of Zcash output descriptions.
pub shielded_outputs: Vec<SaplingOutput<N>>,
/// The balancing value is the net value of spend transfers minus output transfers
/// in a transaction (in zatoshi, represented as a signed integer).
///
/// A positive balancing value takes value from the Sapling value pool,
/// and adds it to the transparent value pool.
///
/// A negative balancing value does the reverse.
pub value_balance: ZcashAmount,