Skip to content

Commit

Permalink
Make txid contents private & use txid for TzeOutPoint
Browse files Browse the repository at this point in the history
  • Loading branch information
nuttycom committed Jun 1, 2021
1 parent 936b552 commit 76999eb
Show file tree
Hide file tree
Showing 7 changed files with 72 additions and 31 deletions.
4 changes: 2 additions & 2 deletions zcash_client_backend/src/data_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -412,14 +412,14 @@ pub mod testing {
&mut self,
_received_tx: &ReceivedTransaction,
) -> Result<Self::TxRef, Self::Error> {
Ok(TxId([0u8; 32]))
Ok(TxId::from_bytes([0u8; 32]))
}

fn store_sent_tx(
&mut self,
_sent_tx: &SentTransaction,
) -> Result<Self::TxRef, Self::Error> {
Ok(TxId([0u8; 32]))
Ok(TxId::from_bytes([0u8; 32]))
}

fn rewind_to_height(&mut self, _block_height: BlockHeight) -> Result<(), Self::Error> {
Expand Down
14 changes: 13 additions & 1 deletion zcash_client_backend/src/proto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@ use zcash_primitives::{
block::{BlockHash, BlockHeader},
consensus::BlockHeight,
sapling::Nullifier,
transaction::components::sapling::{CompactOutputDescription, OutputDescription},
transaction::{
components::sapling::{CompactOutputDescription, OutputDescription},
TxId,
},
};

use zcash_note_encryption::COMPACT_NOTE_SIZE;
Expand Down Expand Up @@ -74,6 +77,15 @@ impl compact_formats::CompactBlock {
}
}

impl compact_formats::CompactTx {
/// Returns the transaction Id
pub fn txid(&self) -> TxId {
let mut hash = [0u8; 32];
hash.copy_from_slice(&self.hash);
TxId::from_bytes(hash)
}
}

impl compact_formats::CompactOutput {
/// Returns the note commitment for this output.
///
Expand Down
16 changes: 9 additions & 7 deletions zcash_client_backend/src/welding_rig.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use zcash_primitives::{
note_encryption::{try_sapling_compact_note_decryption, SaplingDomain},
Node, Note, Nullifier, PaymentAddress, SaplingIvk,
},
transaction::{components::sapling::CompactOutputDescription, TxId},
transaction::components::sapling::CompactOutputDescription,
zip32::ExtendedFullViewingKey,
};

Expand All @@ -32,7 +32,8 @@ use crate::wallet::{AccountId, WalletShieldedOutput, WalletShieldedSpend, Wallet
fn scan_output<P: consensus::Parameters, K: ScanningKey>(
params: &P,
height: BlockHeight,
(index, output): (usize, CompactOutput),
index: usize,
output: CompactOutput,
vks: &[(&AccountId, &K)],
spent_from_accounts: &HashSet<AccountId>,
tree: &mut CommitmentTree<Node>,
Expand Down Expand Up @@ -198,6 +199,8 @@ pub fn scan_block<P: consensus::Parameters, K: ScanningKey>(
let block_height = block.height();

for tx in block.vtx.into_iter() {
let txid = tx.txid();
let index = tx.index as usize;
let num_spends = tx.spends.len();
let num_outputs = tx.outputs.len();

Expand Down Expand Up @@ -249,7 +252,7 @@ pub fn scan_block<P: consensus::Parameters, K: ScanningKey>(
})
.collect();

for to_scan in tx.outputs.into_iter().enumerate() {
for (idx, c_out) in tx.outputs.into_iter().enumerate() {
// Grab mutable references to new witnesses from previous outputs
// in this transaction so that we can update them. Scoped so we
// don't hold mutable references to shielded_outputs for too long.
Expand All @@ -261,7 +264,8 @@ pub fn scan_block<P: consensus::Parameters, K: ScanningKey>(
if let Some(output) = scan_output(
params,
block_height,
to_scan,
idx,
c_out,
vks,
&spent_from_accounts,
tree,
Expand All @@ -275,11 +279,9 @@ pub fn scan_block<P: consensus::Parameters, K: ScanningKey>(
}

if !(shielded_spends.is_empty() && shielded_outputs.is_empty()) {
let mut txid = TxId([0u8; 32]);
txid.0.copy_from_slice(&tx.hash);
wtxs.push(WalletTx {
txid,
index: tx.index as usize,
index,
num_spends,
num_outputs,
shielded_spends,
Expand Down
8 changes: 4 additions & 4 deletions zcash_client_sqlite/src/wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -389,7 +389,7 @@ pub fn block_height_extrema<P>(
///
/// let data_file = NamedTempFile::new().unwrap();
/// let db = WalletDb::for_path(data_file, Network::TestNetwork).unwrap();
/// let height = get_tx_height(&db, TxId([0u8; 32]));
/// let height = get_tx_height(&db, TxId::from_bytes([0u8; 32]));
/// ```
pub fn get_tx_height<P>(
wdb: &WalletDb<P>,
Expand All @@ -398,7 +398,7 @@ pub fn get_tx_height<P>(
wdb.conn
.query_row(
"SELECT block FROM transactions WHERE txid = ?",
&[txid.0.to_vec()],
&[txid.as_ref().to_vec()],
|row| row.get(0).map(u32::into),
)
.optional()
Expand Down Expand Up @@ -616,7 +616,7 @@ pub fn put_tx_meta<'a, P, N>(
tx: &WalletTx<N>,
height: BlockHeight,
) -> Result<i64, SqliteClientError> {
let txid = tx.txid.0.to_vec();
let txid = tx.txid.as_ref().to_vec();
if stmts
.stmt_update_tx_meta
.execute(params![u32::from(height), (tx.index as i64), txid])?
Expand All @@ -643,7 +643,7 @@ pub fn put_tx_data<'a, P>(
tx: &Transaction,
created_at: Option<time::OffsetDateTime>,
) -> Result<i64, SqliteClientError> {
let txid = tx.txid().0.to_vec();
let txid = tx.txid().as_ref().to_vec();

let mut raw_tx = vec![];
tx.write(&mut raw_tx)?;
Expand Down
8 changes: 4 additions & 4 deletions zcash_extensions/src/transparent/demo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -625,7 +625,7 @@ mod tests {
//

let in_b = TzeIn {
prevout: TzeOutPoint::new(tx_a.txid().0, 0),
prevout: TzeOutPoint::new(tx_a.txid(), 0),
witness: tze::Witness::from(0, &Witness::open(preimage_1)),
};
let out_b = TzeOut {
Expand All @@ -642,7 +642,7 @@ mod tests {
//

let in_c = TzeIn {
prevout: TzeOutPoint::new(tx_b.txid().0, 0),
prevout: TzeOutPoint::new(tx_b.txid(), 0),
witness: tze::Witness::from(0, &Witness::close(preimage_2)),
};

Expand Down Expand Up @@ -737,7 +737,7 @@ mod tests {
extension_id: 0,
};
let prevout_a = (
TzeOutPoint::new(tx_a.txid().0, 0),
TzeOutPoint::new(tx_a.txid(), 0),
tx_a.tze_outputs[0].clone(),
);
let value_xfr = (value - DEFAULT_FEE).unwrap();
Expand All @@ -759,7 +759,7 @@ mod tests {
extension_id: 0,
};
let prevout_b = (
TzeOutPoint::new(tx_a.txid().0, 0),
TzeOutPoint::new(tx_a.txid(), 0),
tx_b.tze_outputs[0].clone(),
);
db_c.demo_close(prevout_b, preimage_2)
Expand Down
18 changes: 9 additions & 9 deletions zcash_primitives/src/transaction/components/tze.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use std::convert::TryFrom;
use crate::{
extensions::transparent as tze,
serialize::{CompactSize, Vector},
transaction::TxId,
};

use super::amount::Amount;
Expand All @@ -20,33 +21,32 @@ fn to_io_error(_: std::num::TryFromIntError) -> io::Error {

#[derive(Clone, Debug, PartialEq)]
pub struct TzeOutPoint {
hash: [u8; 32],
txid: TxId,
n: u32,
}

impl TzeOutPoint {
pub fn new(hash: [u8; 32], n: u32) -> Self {
TzeOutPoint { hash, n }
pub fn new(txid: TxId, n: u32) -> Self {
TzeOutPoint { txid, n }
}

pub fn read<R: Read>(mut reader: R) -> io::Result<Self> {
let mut hash = [0u8; 32];
reader.read_exact(&mut hash)?;
let txid = TxId::read(&mut reader)?;
let n = reader.read_u32::<LittleEndian>()?;
Ok(TzeOutPoint { hash, n })
Ok(TzeOutPoint { txid, n })
}

pub fn write<W: Write>(&self, mut writer: W) -> io::Result<()> {
writer.write_all(&self.hash)?;
self.txid.write(&mut writer)?;
writer.write_u32::<LittleEndian>(self.n)
}

pub fn n(&self) -> u32 {
self.n
}

pub fn hash(&self) -> &[u8; 32] {
&self.hash
pub fn txid(&self) -> &TxId {
&self.txid
}
}

Expand Down
35 changes: 31 additions & 4 deletions zcash_primitives/src/transaction/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ const ZFUTURE_VERSION_GROUP_ID: u32 = 0xFFFFFFFF;
const ZFUTURE_TX_VERSION: u32 = 0x0000FFFF;

#[derive(Clone, Copy, Debug, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct TxId(pub [u8; 32]);
pub struct TxId([u8; 32]);

impl fmt::Display for TxId {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
Expand All @@ -51,6 +51,29 @@ impl fmt::Display for TxId {
}
}

impl AsRef<[u8; 32]> for TxId {
fn as_ref(&self) -> &[u8; 32] {
&self.0
}
}

impl TxId {
pub fn from_bytes(bytes: [u8; 32]) -> Self {
TxId(bytes)
}

pub fn read<R: Read>(mut reader: R) -> io::Result<Self> {
let mut hash = [0u8; 32];
reader.read_exact(&mut hash)?;
Ok(TxId::from_bytes(hash))
}

pub fn write<W: Write>(&self, mut writer: W) -> io::Result<()> {
writer.write_all(&self.0)?;
Ok(())
}
}

/// The set of defined transaction format versions.
///
/// This is serialized in the first four or eight bytes of the transaction format, and
Expand Down Expand Up @@ -502,7 +525,7 @@ pub mod testing {

use super::{
components::{amount::MAX_MONEY, Amount, OutPoint, TxIn, TxOut},
Transaction, TransactionData, TxVersion,
Transaction, TransactionData, TxId, TxVersion,
};

#[cfg(feature = "zfuture")]
Expand All @@ -519,6 +542,10 @@ pub mod testing {
0x6a, // OP_RETURN,
];

pub fn arb_txid() -> impl Strategy<Value = TxId> {
prop::array::uniform32(any::<u8>()).prop_map(TxId::from_bytes)
}

prop_compose! {
pub fn arb_outpoint()(hash in prop::array::uniform32(1u8..), n in 1..100u32) -> OutPoint {
OutPoint::new(hash, n)
Expand Down Expand Up @@ -551,8 +578,8 @@ pub mod testing {

#[cfg(feature = "zfuture")]
prop_compose! {
pub fn arb_tzeoutpoint()(hash in prop::array::uniform32(1u8..), n in 1..100u32) -> TzeOutPoint {
TzeOutPoint::new(hash, n)
pub fn arb_tzeoutpoint()(txid in arb_txid(), n in 1..100u32) -> TzeOutPoint {
TzeOutPoint::new(txid, n)
}
}

Expand Down

0 comments on commit 76999eb

Please sign in to comment.