-
Notifications
You must be signed in to change notification settings - Fork 986
/
Copy pathmasp.rs
2321 lines (2181 loc) · 87.4 KB
/
masp.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
//! MASP verification wrappers.
use std::collections::{btree_map, BTreeMap, BTreeSet, HashMap, HashSet};
use std::env;
use std::fmt::Debug;
use std::ops::Deref;
use std::path::PathBuf;
// use async_std::io::prelude::WriteExt;
// use async_std::io::{self};
use borsh::{BorshDeserialize, BorshSerialize};
use borsh_ext::BorshSerializeExt;
use itertools::Either;
use lazy_static::lazy_static;
use masp_primitives::asset_type::AssetType;
#[cfg(feature = "mainnet")]
use masp_primitives::consensus::MainNetwork;
#[cfg(not(feature = "mainnet"))]
use masp_primitives::consensus::TestNetwork;
use masp_primitives::convert::AllowedConversion;
use masp_primitives::ff::PrimeField;
use masp_primitives::group::GroupEncoding;
use masp_primitives::memo::MemoBytes;
use masp_primitives::merkle_tree::{
CommitmentTree, IncrementalWitness, MerklePath,
};
use masp_primitives::sapling::keys::FullViewingKey;
use masp_primitives::sapling::note_encryption::*;
use masp_primitives::sapling::redjubjub::PublicKey;
use masp_primitives::sapling::{
Diversifier, Node, Note, Nullifier, ViewingKey,
};
use masp_primitives::transaction::builder::{self, *};
use masp_primitives::transaction::components::sapling::builder::SaplingMetadata;
use masp_primitives::transaction::components::transparent::builder::TransparentBuilder;
use masp_primitives::transaction::components::{
ConvertDescription, I128Sum, OutputDescription, SpendDescription, TxOut,
U64Sum,
};
use masp_primitives::transaction::fees::fixed::FeeRule;
use masp_primitives::transaction::sighash::{signature_hash, SignableInput};
use masp_primitives::transaction::txid::TxIdDigester;
use masp_primitives::transaction::{
Authorization, Authorized, Transaction, TransactionData,
TransparentAddress, Unauthorized,
};
use masp_primitives::zip32::{ExtendedFullViewingKey, ExtendedSpendingKey};
use masp_proofs::bellman::groth16::PreparedVerifyingKey;
use masp_proofs::bls12_381::Bls12;
use masp_proofs::prover::LocalTxProver;
use masp_proofs::sapling::SaplingVerificationContext;
use namada_core::types::address::{Address, MASP};
use namada_core::types::masp::{
BalanceOwner, ExtendedViewingKey, PaymentAddress, TransferSource,
TransferTarget,
};
use namada_core::types::storage::{BlockHeight, Epoch, Key, KeySeg, TxIndex};
use namada_core::types::time::{DateTimeUtc, DurationSecs};
use namada_core::types::token;
use namada_core::types::token::{
Change, MaspDenom, Transfer, HEAD_TX_KEY, PIN_KEY_PREFIX, TX_KEY_PREFIX,
};
use namada_core::types::transaction::WrapperTx;
use rand_core::{CryptoRng, OsRng, RngCore};
use ripemd::Digest as RipemdDigest;
use sha2::Digest;
use thiserror::Error;
#[cfg(feature = "testing")]
use crate::error::EncodingError;
use crate::error::{Error, PinnedBalanceError, QueryError};
use crate::io::Io;
use crate::proto::Tx;
use crate::queries::Client;
use crate::rpc::{query_conversion, query_storage_value};
use crate::tendermint_rpc::query::Query;
use crate::tendermint_rpc::Order;
use crate::tx::decode_component;
use crate::{display_line, edisplay_line, rpc, MaybeSend, MaybeSync, Namada};
/// Env var to point to a dir with MASP parameters. When not specified,
/// the default OS specific path is used.
pub const ENV_VAR_MASP_PARAMS_DIR: &str = "NAMADA_MASP_PARAMS_DIR";
/// Env var to either "save" proofs into files or to "load" them from
/// files.
pub const ENV_VAR_MASP_TEST_PROOFS: &str = "NAMADA_MASP_TEST_PROOFS";
/// Randomness seed for MASP integration tests to build proofs with
/// deterministic rng.
pub const ENV_VAR_MASP_TEST_SEED: &str = "NAMADA_MASP_TEST_SEED";
/// A directory to save serialized proofs for tests.
pub const MASP_TEST_PROOFS_DIR: &str = "test_fixtures/masp_proofs";
/// The network to use for MASP
#[cfg(feature = "mainnet")]
const NETWORK: MainNetwork = MainNetwork;
#[cfg(not(feature = "mainnet"))]
const NETWORK: TestNetwork = TestNetwork;
// TODO these could be exported from masp_proof crate
/// Spend circuit name
pub const SPEND_NAME: &str = "masp-spend.params";
/// Output circuit name
pub const OUTPUT_NAME: &str = "masp-output.params";
/// Convert circuit name
pub const CONVERT_NAME: &str = "masp-convert.params";
/// Shielded transfer
#[derive(Clone, Debug, BorshSerialize, BorshDeserialize)]
pub struct ShieldedTransfer {
/// Shielded transfer builder
pub builder: Builder<(), (), ExtendedFullViewingKey, ()>,
/// MASP transaction
pub masp_tx: Transaction,
/// Metadata
pub metadata: SaplingMetadata,
/// Epoch in which the transaction was created
pub epoch: Epoch,
}
#[cfg(feature = "testing")]
#[derive(Clone, Copy, Debug)]
enum LoadOrSaveProofs {
Load,
Save,
Neither,
}
/// A return type for gen_shielded_transfer
#[derive(Error, Debug)]
pub enum TransferErr {
/// Build error for masp errors
#[error("{0}")]
Build(#[from] builder::Error<std::convert::Infallible>),
/// errors
#[error("{0}")]
General(#[from] Error),
}
/// MASP verifying keys
pub struct PVKs {
/// spend verifying key
spend_vk: PreparedVerifyingKey<Bls12>,
/// convert verifying key
convert_vk: PreparedVerifyingKey<Bls12>,
/// output verifying key
output_vk: PreparedVerifyingKey<Bls12>,
}
lazy_static! {
/// MASP verifying keys load from parameters
static ref VERIFIYING_KEYS: PVKs =
{
let params_dir = get_params_dir();
let [spend_path, convert_path, output_path] =
[SPEND_NAME, CONVERT_NAME, OUTPUT_NAME].map(|p| params_dir.join(p));
#[cfg(feature = "download-params")]
if !spend_path.exists() || !convert_path.exists() || !output_path.exists() {
let paths = masp_proofs::download_masp_parameters(None).expect(
"MASP parameters were not present, expected the download to \
succeed",
);
if paths.spend != spend_path
|| paths.convert != convert_path
|| paths.output != output_path
{
panic!(
"unrecoverable: downloaded missing masp params, but to an \
unfamiliar path"
)
}
}
// size and blake2b checked here
let params = masp_proofs::load_parameters(
spend_path.as_path(),
output_path.as_path(),
convert_path.as_path(),
);
PVKs {
spend_vk: params.spend_vk,
convert_vk: params.convert_vk,
output_vk: params.output_vk
}
};
}
/// Make sure the MASP params are present and load verifying keys into memory
pub fn preload_verifying_keys() -> &'static PVKs {
&VERIFIYING_KEYS
}
fn load_pvks() -> &'static PVKs {
&VERIFIYING_KEYS
}
/// check_spend wrapper
pub fn check_spend(
spend: &SpendDescription<<Authorized as Authorization>::SaplingAuth>,
sighash: &[u8; 32],
ctx: &mut SaplingVerificationContext,
parameters: &PreparedVerifyingKey<Bls12>,
) -> bool {
let zkproof =
masp_proofs::bellman::groth16::Proof::read(spend.zkproof.as_slice());
let zkproof = match zkproof {
Ok(zkproof) => zkproof,
_ => return false,
};
ctx.check_spend(
spend.cv,
spend.anchor,
&spend.nullifier.0,
PublicKey(spend.rk.0),
sighash,
spend.spend_auth_sig,
zkproof,
parameters,
)
}
/// check_output wrapper
pub fn check_output(
output: &OutputDescription<<<Authorized as Authorization>::SaplingAuth as masp_primitives::transaction::components::sapling::Authorization>::Proof>,
ctx: &mut SaplingVerificationContext,
parameters: &PreparedVerifyingKey<Bls12>,
) -> bool {
let zkproof =
masp_proofs::bellman::groth16::Proof::read(output.zkproof.as_slice());
let zkproof = match zkproof {
Ok(zkproof) => zkproof,
_ => return false,
};
let epk =
masp_proofs::jubjub::ExtendedPoint::from_bytes(&output.ephemeral_key.0);
let epk = match epk.into() {
Some(p) => p,
None => return false,
};
ctx.check_output(output.cv, output.cmu, epk, zkproof, parameters)
}
/// check convert wrapper
pub fn check_convert(
convert: &ConvertDescription<<<Authorized as Authorization>::SaplingAuth as masp_primitives::transaction::components::sapling::Authorization>::Proof>,
ctx: &mut SaplingVerificationContext,
parameters: &PreparedVerifyingKey<Bls12>,
) -> bool {
let zkproof =
masp_proofs::bellman::groth16::Proof::read(convert.zkproof.as_slice());
let zkproof = match zkproof {
Ok(zkproof) => zkproof,
_ => return false,
};
ctx.check_convert(convert.cv, convert.anchor, zkproof, parameters)
}
/// Represents an authorization where the Sapling bundle is authorized and the
/// transparent bundle is unauthorized.
pub struct PartialAuthorized;
impl Authorization for PartialAuthorized {
type SaplingAuth = <Authorized as Authorization>::SaplingAuth;
type TransparentAuth = <Unauthorized as Authorization>::TransparentAuth;
}
/// Partially deauthorize the transparent bundle
fn partial_deauthorize(
tx_data: &TransactionData<Authorized>,
) -> Option<TransactionData<PartialAuthorized>> {
let transp = tx_data.transparent_bundle().and_then(|x| {
let mut tb = TransparentBuilder::empty();
for vin in &x.vin {
tb.add_input(TxOut {
asset_type: vin.asset_type,
value: vin.value,
address: vin.address,
})
.ok()?;
}
for vout in &x.vout {
tb.add_output(&vout.address, vout.asset_type, vout.value)
.ok()?;
}
tb.build()
});
if tx_data.transparent_bundle().is_some() != transp.is_some() {
return None;
}
Some(TransactionData::from_parts(
tx_data.version(),
tx_data.consensus_branch_id(),
tx_data.lock_time(),
tx_data.expiry_height(),
transp,
tx_data.sapling_bundle().cloned(),
))
}
/// Verify a shielded transaction.
pub fn verify_shielded_tx(transaction: &Transaction) -> bool {
tracing::info!("entered verify_shielded_tx()");
let sapling_bundle = if let Some(bundle) = transaction.sapling_bundle() {
bundle
} else {
return false;
};
let tx_data = transaction.deref();
// Partially deauthorize the transparent bundle
let unauth_tx_data = match partial_deauthorize(tx_data) {
Some(tx_data) => tx_data,
None => return false,
};
let txid_parts = unauth_tx_data.digest(TxIdDigester);
// the commitment being signed is shared across all Sapling inputs; once
// V4 transactions are deprecated this should just be the txid, but
// for now we need to continue to compute it here.
let sighash =
signature_hash(&unauth_tx_data, &SignableInput::Shielded, &txid_parts);
tracing::info!("sighash computed");
let PVKs {
spend_vk,
convert_vk,
output_vk,
} = load_pvks();
let mut ctx = SaplingVerificationContext::new(true);
let spends_valid = sapling_bundle
.shielded_spends
.iter()
.all(|spend| check_spend(spend, sighash.as_ref(), &mut ctx, spend_vk));
let converts_valid = sapling_bundle
.shielded_converts
.iter()
.all(|convert| check_convert(convert, &mut ctx, convert_vk));
let outputs_valid = sapling_bundle
.shielded_outputs
.iter()
.all(|output| check_output(output, &mut ctx, output_vk));
if !(spends_valid && outputs_valid && converts_valid) {
return false;
}
tracing::info!("passed spend/output verification");
let assets_and_values: I128Sum = sapling_bundle.value_balance.clone();
tracing::info!(
"accumulated {} assets/values",
assets_and_values.components().len()
);
let result = ctx.final_check(
assets_and_values,
sighash.as_ref(),
sapling_bundle.authorization.binding_sig,
);
tracing::info!("final check result {result}");
result
}
/// Get the path to MASP parameters from [`ENV_VAR_MASP_PARAMS_DIR`] env var or
/// use the default.
pub fn get_params_dir() -> PathBuf {
if let Ok(params_dir) = env::var(ENV_VAR_MASP_PARAMS_DIR) {
println!("Using {} as masp parameter folder.", params_dir);
PathBuf::from(params_dir)
} else {
masp_proofs::default_params_folder().unwrap()
}
}
/// Freeze a Builder into the format necessary for inclusion in a Tx. This is
/// the format used by hardware wallets to validate a MASP Transaction.
struct WalletMap;
impl<P1>
masp_primitives::transaction::components::sapling::builder::MapBuilder<
P1,
ExtendedSpendingKey,
(),
ExtendedFullViewingKey,
> for WalletMap
{
fn map_params(&self, _s: P1) {}
fn map_key(&self, s: ExtendedSpendingKey) -> ExtendedFullViewingKey {
(&s).into()
}
}
impl<P1, R1, N1>
MapBuilder<
P1,
R1,
ExtendedSpendingKey,
N1,
(),
(),
ExtendedFullViewingKey,
(),
> for WalletMap
{
fn map_rng(&self, _s: R1) {}
fn map_notifier(&self, _s: N1) {}
}
/// Abstracts platform specific details away from the logic of shielded pool
/// operations.
#[cfg_attr(feature = "async-send", async_trait::async_trait)]
#[cfg_attr(not(feature = "async-send"), async_trait::async_trait(?Send))]
pub trait ShieldedUtils:
Sized + BorshDeserialize + BorshSerialize + Default + Clone
{
/// Get a MASP transaction prover
fn local_tx_prover(&self) -> LocalTxProver;
/// Load up the currently saved ShieldedContext
async fn load<U: ShieldedUtils + MaybeSend>(
&self,
ctx: &mut ShieldedContext<U>,
) -> std::io::Result<()>;
/// Save the given ShieldedContext for future loads
async fn save<U: ShieldedUtils + MaybeSync>(
&self,
ctx: &ShieldedContext<U>,
) -> std::io::Result<()>;
}
/// Make a ViewingKey that can view notes encrypted by given ExtendedSpendingKey
pub fn to_viewing_key(esk: &ExtendedSpendingKey) -> FullViewingKey {
ExtendedFullViewingKey::from(esk).fvk
}
/// Generate a valid diversifier, i.e. one that has a diversified base. Return
/// also this diversified base.
pub fn find_valid_diversifier<R: RngCore + CryptoRng>(
rng: &mut R,
) -> (Diversifier, masp_primitives::jubjub::SubgroupPoint) {
let mut diversifier;
let g_d;
// Keep generating random diversifiers until one has a diversified base
loop {
let mut d = [0; 11];
rng.fill_bytes(&mut d);
diversifier = Diversifier(d);
if let Some(val) = diversifier.g_d() {
g_d = val;
break;
}
}
(diversifier, g_d)
}
/// Determine if using the current note would actually bring us closer to our
/// target
pub fn is_amount_required(src: I128Sum, dest: I128Sum, delta: I128Sum) -> bool {
let gap = dest - src;
for (asset_type, value) in gap.components() {
if *value >= 0 && delta[asset_type] >= 0 {
return true;
}
}
false
}
// #[derive(BorshSerialize, BorshDeserialize, Debug, Clone)]
// pub struct MaspAmount {
// pub asset: Address,
// pub amount: token::Amount,
// }
/// a masp change
#[derive(BorshSerialize, BorshDeserialize, Debug, Clone)]
pub struct MaspChange {
/// the token address
pub asset: Address,
/// the change in the token
pub change: token::Change,
}
/// a masp amount
#[derive(
BorshSerialize, BorshDeserialize, Debug, Clone, Default, PartialEq, Eq,
)]
pub struct MaspAmount(HashMap<(Epoch, Address), token::Change>);
impl std::ops::Deref for MaspAmount {
type Target = HashMap<(Epoch, Address), token::Change>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl std::ops::DerefMut for MaspAmount {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl std::ops::Add for MaspAmount {
type Output = MaspAmount;
fn add(mut self, mut rhs: MaspAmount) -> Self::Output {
for (key, value) in rhs.drain() {
self.entry(key)
.and_modify(|val| *val += value)
.or_insert(value);
}
self.retain(|_, v| !v.is_zero());
self
}
}
impl std::ops::AddAssign for MaspAmount {
fn add_assign(&mut self, amount: MaspAmount) {
*self = self.clone() + amount
}
}
// please stop copying and pasting make a function
impl std::ops::Sub for MaspAmount {
type Output = MaspAmount;
fn sub(mut self, mut rhs: MaspAmount) -> Self::Output {
for (key, value) in rhs.drain() {
self.entry(key)
.and_modify(|val| *val -= value)
.or_insert(-value);
}
self.0.retain(|_, v| !v.is_zero());
self
}
}
impl std::ops::SubAssign for MaspAmount {
fn sub_assign(&mut self, amount: MaspAmount) {
*self = self.clone() - amount
}
}
impl std::ops::Mul<Change> for MaspAmount {
type Output = Self;
fn mul(mut self, rhs: Change) -> Self::Output {
for (_, value) in self.iter_mut() {
*value = *value * rhs
}
self
}
}
impl<'a> From<&'a MaspAmount> for I128Sum {
fn from(masp_amount: &'a MaspAmount) -> I128Sum {
let mut res = I128Sum::zero();
for ((epoch, token), val) in masp_amount.iter() {
for denom in MaspDenom::iter() {
let asset =
make_asset_type(Some(*epoch), token, denom).unwrap();
res += I128Sum::from_pair(asset, denom.denominate_i128(val))
.unwrap();
}
}
res
}
}
impl From<MaspAmount> for I128Sum {
fn from(amt: MaspAmount) -> Self {
Self::from(&amt)
}
}
/// Represents the amount used of different conversions
pub type Conversions =
BTreeMap<AssetType, (AllowedConversion, MerklePath<Node>, i128)>;
/// Represents the changes that were made to a list of transparent accounts
pub type TransferDelta = HashMap<Address, MaspChange>;
/// Represents the changes that were made to a list of shielded accounts
pub type TransactionDelta = HashMap<ViewingKey, MaspAmount>;
/// Represents the current state of the shielded pool from the perspective of
/// the chosen viewing keys.
#[derive(BorshSerialize, BorshDeserialize, Debug)]
pub struct ShieldedContext<U: ShieldedUtils> {
/// Location where this shielded context is saved
#[borsh(skip)]
pub utils: U,
/// The last transaction index to be processed in this context
pub last_txidx: u64,
/// The commitment tree produced by scanning all transactions up to tx_pos
pub tree: CommitmentTree<Node>,
/// Maps viewing keys to applicable note positions
pub pos_map: HashMap<ViewingKey, BTreeSet<usize>>,
/// Maps a nullifier to the note position to which it applies
pub nf_map: HashMap<Nullifier, usize>,
/// Maps note positions to their corresponding notes
pub note_map: HashMap<usize, Note>,
/// Maps note positions to their corresponding memos
pub memo_map: HashMap<usize, MemoBytes>,
/// Maps note positions to the diversifier of their payment address
pub div_map: HashMap<usize, Diversifier>,
/// Maps note positions to their witness (used to make merkle paths)
pub witness_map: HashMap<usize, IncrementalWitness<Node>>,
/// Tracks what each transaction does to various account balances
pub delta_map: BTreeMap<
(BlockHeight, TxIndex),
(Epoch, TransferDelta, TransactionDelta),
>,
/// The set of note positions that have been spent
pub spents: HashSet<usize>,
/// Maps asset types to their decodings
pub asset_types: HashMap<AssetType, (Address, MaspDenom, Epoch)>,
/// Maps note positions to their corresponding viewing keys
pub vk_map: HashMap<usize, ViewingKey>,
}
/// Default implementation to ease construction of TxContexts. Derive cannot be
/// used here due to CommitmentTree not implementing Default.
impl<U: ShieldedUtils + Default> Default for ShieldedContext<U> {
fn default() -> ShieldedContext<U> {
ShieldedContext::<U> {
utils: U::default(),
last_txidx: u64::default(),
tree: CommitmentTree::empty(),
pos_map: HashMap::default(),
nf_map: HashMap::default(),
note_map: HashMap::default(),
memo_map: HashMap::default(),
div_map: HashMap::default(),
witness_map: HashMap::default(),
spents: HashSet::default(),
delta_map: BTreeMap::default(),
asset_types: HashMap::default(),
vk_map: HashMap::default(),
}
}
}
impl<U: ShieldedUtils + MaybeSend + MaybeSync> ShieldedContext<U> {
/// Try to load the last saved shielded context from the given context
/// directory. If this fails, then leave the current context unchanged.
pub async fn load(&mut self) -> std::io::Result<()> {
self.utils.clone().load(self).await
}
/// Save this shielded context into its associated context directory
pub async fn save(&self) -> std::io::Result<()> {
self.utils.save(self).await
}
/// Merge data from the given shielded context into the current shielded
/// context. It must be the case that the two shielded contexts share the
/// same last transaction ID and share identical commitment trees.
pub fn merge(&mut self, new_ctx: ShieldedContext<U>) {
debug_assert_eq!(self.last_txidx, new_ctx.last_txidx);
// Merge by simply extending maps. Identical keys should contain
// identical values, so overwriting should not be problematic.
self.pos_map.extend(new_ctx.pos_map);
self.nf_map.extend(new_ctx.nf_map);
self.note_map.extend(new_ctx.note_map);
self.memo_map.extend(new_ctx.memo_map);
self.div_map.extend(new_ctx.div_map);
self.witness_map.extend(new_ctx.witness_map);
self.spents.extend(new_ctx.spents);
self.asset_types.extend(new_ctx.asset_types);
self.vk_map.extend(new_ctx.vk_map);
// The deltas are the exception because different keys can reveal
// different parts of the same transaction. Hence each delta needs to be
// merged separately.
for ((height, idx), (ep, ntfer_delta, ntx_delta)) in new_ctx.delta_map {
let (_ep, tfer_delta, tx_delta) = self
.delta_map
.entry((height, idx))
.or_insert((ep, TransferDelta::new(), TransactionDelta::new()));
tfer_delta.extend(ntfer_delta);
tx_delta.extend(ntx_delta);
}
}
/// Fetch the current state of the multi-asset shielded pool into a
/// ShieldedContext
pub async fn fetch<C: Client + Sync>(
&mut self,
client: &C,
sks: &[ExtendedSpendingKey],
fvks: &[ViewingKey],
) -> Result<(), Error> {
// First determine which of the keys requested to be fetched are new.
// Necessary because old transactions will need to be scanned for new
// keys.
let mut unknown_keys = Vec::new();
for esk in sks {
let vk = to_viewing_key(esk).vk;
if !self.pos_map.contains_key(&vk) {
unknown_keys.push(vk);
}
}
for vk in fvks {
if !self.pos_map.contains_key(vk) {
unknown_keys.push(*vk);
}
}
// If unknown keys are being used, we need to scan older transactions
// for any unspent notes
let (txs, mut tx_iter);
if !unknown_keys.is_empty() {
// Load all transactions accepted until this point
txs = Self::fetch_shielded_transfers(client, 0).await?;
tx_iter = txs.iter();
// Do this by constructing a shielding context only for unknown keys
let mut tx_ctx = Self {
utils: self.utils.clone(),
..Default::default()
};
for vk in unknown_keys {
tx_ctx.pos_map.entry(vk).or_insert_with(BTreeSet::new);
}
// Update this unknown shielded context until it is level with self
while tx_ctx.last_txidx != self.last_txidx {
if let Some(((height, idx), (epoch, tx, stx))) = tx_iter.next()
{
tx_ctx
.scan_tx(client, *height, *idx, *epoch, tx, stx)
.await?;
} else {
break;
}
}
// Merge the context data originating from the unknown keys into the
// current context
self.merge(tx_ctx);
} else {
// Load only transactions accepted from last_txid until this point
txs =
Self::fetch_shielded_transfers(client, self.last_txidx).await?;
tx_iter = txs.iter();
}
// Now that we possess the unspent notes corresponding to both old and
// new keys up until tx_pos, proceed to scan the new transactions.
for ((height, idx), (epoch, tx, stx)) in &mut tx_iter {
self.scan_tx(client, *height, *idx, *epoch, tx, stx).await?;
}
Ok(())
}
/// Obtain a chronologically-ordered list of all accepted shielded
/// transactions from the ledger. The ledger conceptually stores
/// transactions as a vector. More concretely, the HEAD_TX_KEY location
/// stores the index of the last accepted transaction and each transaction
/// is stored at a key derived from its index.
pub async fn fetch_shielded_transfers<C: Client + Sync>(
client: &C,
last_txidx: u64,
) -> Result<
BTreeMap<(BlockHeight, TxIndex), (Epoch, Transfer, Transaction)>,
Error,
> {
// The address of the MASP account
let masp_addr = MASP;
// Construct the key where last transaction pointer is stored
let head_tx_key = Key::from(masp_addr.to_db_key())
.push(&HEAD_TX_KEY.to_owned())
.map_err(|k| {
Error::Other(format!("Cannot obtain a storage key: {}", k))
})?;
// Query for the index of the last accepted transaction
let head_txidx = query_storage_value::<C, u64>(client, &head_tx_key)
.await
.unwrap_or(0);
let mut shielded_txs = BTreeMap::new();
// Fetch all the transactions we do not have yet
for i in last_txidx..head_txidx {
// Construct the key for where the current transaction is stored
let current_tx_key = Key::from(masp_addr.to_db_key())
.push(&(TX_KEY_PREFIX.to_owned() + &i.to_string()))
.map_err(|e| {
Error::Other(format!("Cannot obtain a storage key {}", e))
})?;
// Obtain the current transaction
let (tx_epoch, tx_height, tx_index, current_tx, current_stx) =
query_storage_value::<
C,
(Epoch, BlockHeight, TxIndex, Transfer, Transaction),
>(client, ¤t_tx_key)
.await?;
// Collect the current transaction
shielded_txs.insert(
(tx_height, tx_index),
(tx_epoch, current_tx, current_stx),
);
}
Ok(shielded_txs)
}
/// Applies the given transaction to the supplied context. More precisely,
/// the shielded transaction's outputs are added to the commitment tree.
/// Newly discovered notes are associated to the supplied viewing keys. Note
/// nullifiers are mapped to their originating notes. Note positions are
/// associated to notes, memos, and diversifiers. And the set of notes that
/// we have spent are updated. The witness map is maintained to make it
/// easier to construct note merkle paths in other code. See
/// <https://zips.z.cash/protocol/protocol.pdf#scan>
pub async fn scan_tx<C: Client + Sync>(
&mut self,
client: &C,
height: BlockHeight,
index: TxIndex,
epoch: Epoch,
tx: &Transfer,
shielded: &Transaction,
) -> Result<(), Error> {
// For tracking the account changes caused by this Transaction
let mut transaction_delta = TransactionDelta::new();
// Listen for notes sent to our viewing keys
for so in shielded
.sapling_bundle()
.map_or(&vec![], |x| &x.shielded_outputs)
{
// Create merkle tree leaf node from note commitment
let node = Node::new(so.cmu.to_repr());
// Update each merkle tree in the witness map with the latest
// addition
for (_, witness) in self.witness_map.iter_mut() {
witness.append(node).map_err(|()| {
Error::Other("note commitment tree is full".to_string())
})?;
}
let note_pos = self.tree.size();
self.tree.append(node).map_err(|()| {
Error::Other("note commitment tree is full".to_string())
})?;
// Finally, make it easier to construct merkle paths to this new
// note
let witness = IncrementalWitness::<Node>::from_tree(&self.tree);
self.witness_map.insert(note_pos, witness);
// Let's try to see if any of our viewing keys can decrypt latest
// note
let mut pos_map = HashMap::new();
std::mem::swap(&mut pos_map, &mut self.pos_map);
for (vk, notes) in pos_map.iter_mut() {
let decres = try_sapling_note_decryption::<_, OutputDescription<<<Authorized as Authorization>::SaplingAuth as masp_primitives::transaction::components::sapling::Authorization>::Proof>>(
&NETWORK,
1.into(),
&PreparedIncomingViewingKey::new(&vk.ivk()),
so,
);
// So this current viewing key does decrypt this current note...
if let Some((note, pa, memo)) = decres {
// Add this note to list of notes decrypted by this viewing
// key
notes.insert(note_pos);
// Compute the nullifier now to quickly recognize when spent
let nf = note.nf(
&vk.nk,
note_pos.try_into().map_err(|_| {
Error::Other("Can not get nullifier".to_string())
})?,
);
self.note_map.insert(note_pos, note);
self.memo_map.insert(note_pos, memo);
// The payment address' diversifier is required to spend
// note
self.div_map.insert(note_pos, *pa.diversifier());
self.nf_map.insert(nf, note_pos);
// Note the account changes
let balance = transaction_delta
.entry(*vk)
.or_insert_with(MaspAmount::default);
*balance += self
.decode_all_amounts(
client,
I128Sum::from_nonnegative(
note.asset_type,
note.value as i128,
)
.map_err(|()| {
Error::Other(
"found note with invalid value or asset \
type"
.to_string(),
)
})?,
)
.await;
self.vk_map.insert(note_pos, *vk);
break;
}
}
std::mem::swap(&mut pos_map, &mut self.pos_map);
}
// Cancel out those of our notes that have been spent
for ss in shielded
.sapling_bundle()
.map_or(&vec![], |x| &x.shielded_spends)
{
// If the shielded spend's nullifier is in our map, then target note
// is rendered unusable
if let Some(note_pos) = self.nf_map.get(&ss.nullifier) {
self.spents.insert(*note_pos);
// Note the account changes
let balance = transaction_delta
.entry(self.vk_map[note_pos])
.or_insert_with(MaspAmount::default);
let note = self.note_map[note_pos];
*balance -= self
.decode_all_amounts(
client,
I128Sum::from_nonnegative(
note.asset_type,
note.value as i128,
)
.map_err(|()| {
Error::Other(
"found note with invalid value or asset type"
.to_string(),
)
})?,
)
.await;
}
}
// Record the changes to the transparent accounts
let mut transfer_delta = TransferDelta::new();
let token_addr = tx.token.clone();
transfer_delta.insert(
tx.source.clone(),
MaspChange {
asset: token_addr,
change: -tx.amount.amount().change(),
},
);
self.last_txidx += 1;
self.delta_map.insert(
(height, index),
(epoch, transfer_delta, transaction_delta),
);
Ok(())
}
/// Summarize the effects on shielded and transparent accounts of each
/// Transfer in this context
pub fn get_tx_deltas(
&self,
) -> &BTreeMap<
(BlockHeight, TxIndex),
(Epoch, TransferDelta, TransactionDelta),
> {
&self.delta_map
}
/// Compute the total unspent notes associated with the viewing key in the
/// context. If the key is not in the context, then we do not know the
/// balance and hence we return None.
pub async fn compute_shielded_balance<C: Client + Sync>(
&mut self,
client: &C,
vk: &ViewingKey,
) -> Result<Option<MaspAmount>, Error> {
// Cannot query the balance of a key that's not in the map
if !self.pos_map.contains_key(vk) {
return Ok(None);
}
let mut val_acc = I128Sum::zero();
// Retrieve the notes that can be spent by this key
if let Some(avail_notes) = self.pos_map.get(vk) {
for note_idx in avail_notes {
// Spent notes cannot contribute a new transaction's pool
if self.spents.contains(note_idx) {
continue;
}
// Get note associated with this ID
let note = self.note_map.get(note_idx).ok_or_else(|| {
Error::Other(format!("Unable to get note {note_idx}"))
})?;
// Finally add value to multi-asset accumulator
val_acc += I128Sum::from_nonnegative(
note.asset_type,
note.value as i128,
)
.map_err(|()| {
Error::Other(
"found note with invalid value or asset type"
.to_string(),