• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

tari-project / tari / 19227006544

10 Nov 2025 09:31AM UTC coverage: 51.608% (-7.9%) from 59.471%
19227006544

push

github

web-flow
feat: add deterministic transaction id (#7541)

Description
---
Added deterministic transaction IDs, which are an 8-byte (u64) hash
based on the transaction output hash in question and the wallet view
key.
- Any scanned or recovered wallet output will have the same transaction
ID across view or spend wallets.
- Sender wallets will be able to calculate the transaction ID for
receiver wallets if they need to, for that specific output.
- Sender wallets will use their change output as the determining output
hash for the transaction; this will result in the same transaction ID
being allocated upon wallet recovery. In the case of no change output,
the hash of the first ordered output will be used for the transaction
ID.
- For coin split transactions, the hash of the first ordered output will
be used for the transaction ID.

Fixed the issue with the Windows test build target link:
```
: error LNK2019: unresolved external symbol __imp_InitializeSecurityDescriptor referenced in function mdb_env_setup_locks
: error LNK2019: unresolved external symbol __imp_SetSecurityDescriptorDacl referenced in function mdb_env_setup_lock
```

Fixes #7485.

Motivation and Context
---
See #7485.

How Has This Been Tested?
---
Added unit tests.
Performed system-level testing.

What process can a PR reviewer use to test or verify this change?
---
Code review.
System-level testing.

<!-- Checklist -->
<!-- 1. Is the title of your PR in the form that would make nice release
notes? The title, excluding the conventional commit
tag, will be included exactly as is in the CHANGELOG, so please think
about it carefully. -->


Breaking Changes
---

- [x] None
- [ ] Requires data directory on base node to be deleted
- [ ] Requires hard fork
- [ ] Other - Please specify

<!-- Does this include a breaking change? If so, include this line as a
footer -->
<!-- BREAKING CHANGE: Description what the user should do, e.g. delete a
database, resync the chain -->


<!-- This is an auto-generated comm... (continued)

52 of 1260 new or added lines in 14 files covered. (4.13%)

9213 existing lines in 93 files now uncovered.

59188 of 114687 relevant lines covered (51.61%)

8172.79 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

35.16
/base_layer/transaction_components/src/transaction_components/encrypted_data.rs
1
// Copyright 2022 The Tari Project
2
//
3
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
4
// following conditions are met:
5
//
6
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
7
// disclaimer.
8
//
9
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
10
// following disclaimer in the documentation and/or other materials provided with the distribution.
11
//
12
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
13
// products derived from this software without specific prior written permission.
14
//
15
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
16
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
17
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
18
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
19
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
20
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
21
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE
22
//
23
// Portions of this file were originally copyrighted (c) 2018 The Grin Developers, issued under the Apache License,
24
// Version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0.
25

26
//! Encrypted data using the extended-nonce variant XChaCha20-Poly1305 encryption with secure random nonce.
27

28
use std::{convert::TryFrom, mem::size_of};
29

30
use blake2::Blake2b;
31
use borsh::{BorshDeserialize, BorshSerialize};
32
use chacha20poly1305::{
33
    aead::{AeadCore, AeadInPlace, Error, OsRng},
34
    KeyInit,
35
    Tag,
36
    XChaCha20Poly1305,
37
    XNonce,
38
};
39
use digest::{consts::U32, generic_array::GenericArray, FixedOutput};
40
use primitive_types::U256;
41
use serde::{Deserialize, Serialize};
42
use tari_common_types::types::{CompressedCommitment, PrivateKey};
43
use tari_crypto::{hashing::DomainSeparatedHasher, keys::SecretKey};
44
use tari_hashing::TransactionSecureNonceKdfDomain;
45
use tari_max_size::MaxSizeBytes;
46
use tari_utilities::{
47
    hex::{from_hex, to_hex, Hex, HexError},
48
    safe_array::SafeArray,
49
    ByteArray,
50
    ByteArrayError,
51
};
52
use thiserror::Error;
53
use zeroize::{Zeroize, Zeroizing};
54

55
use super::EncryptedDataKey;
56
use crate::{transaction_components::MemoField, MicroMinotari};
57

58
// Useful size constants, each in bytes
59
const SIZE_NONCE: usize = size_of::<XNonce>();
60
pub const SIZE_VALUE: usize = size_of::<u64>();
61
const SIZE_MASK: usize = PrivateKey::KEY_LEN;
62
const SIZE_TAG: usize = size_of::<Tag>();
63
pub const SIZE_U256: usize = size_of::<U256>();
64
pub const STATIC_ENCRYPTED_DATA_SIZE_TOTAL: usize = SIZE_NONCE + SIZE_VALUE + SIZE_MASK + SIZE_TAG;
65
pub const MAX_ENCRYPTED_DATA_SIZE: usize = 256 + STATIC_ENCRYPTED_DATA_SIZE_TOTAL;
66

67
// Number of hex characters of encrypted data to display on each side of ellipsis when truncating
68
const DISPLAY_CUTOFF: usize = 16;
69

70
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, Hash, BorshSerialize, BorshDeserialize, Zeroize)]
×
71
pub struct EncryptedData {
72
    #[serde(with = "tari_utilities::serde::hex")]
73
    data: MaxSizeBytes<MAX_ENCRYPTED_DATA_SIZE>,
74
}
75
/// AEAD associated data
76
const ENCRYPTED_DATA_AAD: &[u8] = b"TARI_AAD_VALUE_AND_MASK_EXTEND_NONCE_VARIANT";
77

78
impl EncryptedData {
79
    /// Encrypt the value and mask (with fixed length) using XChaCha20-Poly1305 with a secure random nonce
80
    /// Notes: - This implementation does not require or assume any uniqueness for `encryption_key` or `commitment`
81
    ///        - With the use of a secure random nonce, there's no added security benefit in using the commitment in the
82
    ///          internal key derivation; but it binds the encrypted data to the commitment
83
    ///        - Consecutive calls to this function with the same inputs will produce different ciphertexts
84
    pub fn encrypt_data(
1,311✔
85
        encryption_key: &PrivateKey,
1,311✔
86
        commitment: &CompressedCommitment,
1,311✔
87
        value: MicroMinotari,
1,311✔
88
        mask: &PrivateKey,
1,311✔
89
        memo: MemoField,
1,311✔
90
    ) -> Result<EncryptedData, EncryptedDataError> {
1,311✔
91
        // Encode the value and mask
92
        let mut bytes = Zeroizing::new(vec![0; SIZE_VALUE + SIZE_MASK + memo.get_size()]);
1,311✔
93
        bytes
1,311✔
94
            .get_mut(..SIZE_VALUE)
1,311✔
95
            .expect("Already checked")
1,311✔
96
            .copy_from_slice(value.as_u64().to_le_bytes().as_ref());
1,311✔
97
        bytes
1,311✔
98
            .get_mut(SIZE_VALUE..SIZE_VALUE + SIZE_MASK)
1,311✔
99
            .expect("Already checked")
1,311✔
100
            .copy_from_slice(mask.as_bytes());
1,311✔
101
        bytes
1,311✔
102
            .get_mut(SIZE_VALUE + SIZE_MASK..)
1,311✔
103
            .expect("Already checked")
1,311✔
104
            .copy_from_slice(&memo.to_bytes());
1,311✔
105

106
        // Produce a secure random nonce
107
        let nonce = XChaCha20Poly1305::generate_nonce(&mut OsRng);
1,311✔
108

109
        // Set up the AEAD
110
        let aead_key = kdf_aead(encryption_key, commitment);
1,311✔
111
        let cipher = XChaCha20Poly1305::new(GenericArray::from_slice(aead_key.reveal()));
1,311✔
112

113
        // Encrypt in place
114
        let tag = cipher.encrypt_in_place_detached(&nonce, ENCRYPTED_DATA_AAD, bytes.as_mut_slice())?;
1,311✔
115

116
        // Put everything together: nonce, ciphertext, tag
117
        let mut data = vec![0; STATIC_ENCRYPTED_DATA_SIZE_TOTAL + memo.get_size()];
1,311✔
118
        data.get_mut(..SIZE_TAG).expect("Already checked").copy_from_slice(&tag);
1,311✔
119
        data.get_mut(SIZE_TAG..SIZE_TAG + SIZE_NONCE)
1,311✔
120
            .expect("Already checked")
1,311✔
121
            .copy_from_slice(&nonce);
1,311✔
122
        data.get_mut(SIZE_TAG + SIZE_NONCE..SIZE_TAG + SIZE_NONCE + SIZE_VALUE + SIZE_MASK + memo.get_size())
1,311✔
123
            .expect("Already checked")
1,311✔
124
            .copy_from_slice(bytes.as_slice());
1,311✔
125
        Ok(Self {
126
            data: MaxSizeBytes::try_from(data)
1,311✔
127
                .map_err(|_| EncryptedDataError::IncorrectLength("Data too long".to_string()))?,
1,311✔
128
        })
129
    }
1,311✔
130

131
    /// Authenticate and decrypt the value and mask
132
    /// Note: This design (similar to other AEADs) is not key committing, thus the caller must not rely on successful
133
    ///       decryption to assert that the expected key was used
UNCOV
134
    pub fn decrypt_data(
×
UNCOV
135
        encryption_key: &PrivateKey,
×
UNCOV
136
        commitment: &CompressedCommitment,
×
UNCOV
137
        encrypted_data: &EncryptedData,
×
UNCOV
138
    ) -> Result<(MicroMinotari, PrivateKey, MemoField), EncryptedDataError> {
×
139
        // Extract the nonce, ciphertext, and tag
UNCOV
140
        let tag = Tag::from_slice(
×
UNCOV
141
            encrypted_data
×
UNCOV
142
                .as_bytes()
×
UNCOV
143
                .get(..SIZE_TAG)
×
UNCOV
144
                .ok_or(EncryptedDataError::IncorrectLength("Tag too short".to_string()))?,
×
145
        );
UNCOV
146
        let nonce = XNonce::from_slice(
×
UNCOV
147
            encrypted_data
×
UNCOV
148
                .as_bytes()
×
UNCOV
149
                .get(SIZE_TAG..SIZE_TAG + SIZE_NONCE)
×
UNCOV
150
                .ok_or(EncryptedDataError::IncorrectLength("Data too short".to_string()))?,
×
151
        );
UNCOV
152
        let mut bytes = Zeroizing::new(vec![
×
153
            0;
UNCOV
154
            encrypted_data
×
UNCOV
155
                .data
×
UNCOV
156
                .len()
×
UNCOV
157
                .saturating_sub(SIZE_TAG)
×
UNCOV
158
                .saturating_sub(SIZE_NONCE)
×
159
        ]);
UNCOV
160
        bytes.copy_from_slice(
×
UNCOV
161
            encrypted_data
×
UNCOV
162
                .as_bytes()
×
UNCOV
163
                .get(SIZE_TAG + SIZE_NONCE..)
×
UNCOV
164
                .ok_or(EncryptedDataError::IncorrectLength("Data too short".to_string()))?,
×
165
        );
166

167
        // Set up the AEAD
UNCOV
168
        let aead_key = kdf_aead(encryption_key, commitment);
×
UNCOV
169
        let cipher = XChaCha20Poly1305::new(GenericArray::from_slice(aead_key.reveal()));
×
170

171
        // Decrypt in place
UNCOV
172
        cipher.decrypt_in_place_detached(nonce, ENCRYPTED_DATA_AAD, bytes.as_mut_slice(), tag)?;
×
173

174
        // Decode the value and mask
UNCOV
175
        let mut value_bytes = [0u8; SIZE_VALUE];
×
UNCOV
176
        value_bytes.copy_from_slice(
×
UNCOV
177
            bytes
×
UNCOV
178
                .get(0..SIZE_VALUE)
×
UNCOV
179
                .ok_or(EncryptedDataError::IncorrectLength("Value too short".to_string()))?,
×
180
        );
181
        Ok((
UNCOV
182
            u64::from_le_bytes(value_bytes).into(),
×
UNCOV
183
            PrivateKey::from_canonical_bytes(
×
UNCOV
184
                bytes
×
UNCOV
185
                    .get(SIZE_VALUE..SIZE_VALUE + SIZE_MASK)
×
UNCOV
186
                    .ok_or(EncryptedDataError::IncorrectLength("Data too short".to_string()))?,
×
187
            )?,
×
UNCOV
188
            MemoField::from_bytes(
×
UNCOV
189
                bytes
×
UNCOV
190
                    .get(SIZE_VALUE + SIZE_MASK..)
×
UNCOV
191
                    .ok_or(EncryptedDataError::IncorrectLength("Data too long".to_string()))?,
×
192
            ),
193
        ))
UNCOV
194
    }
×
195

196
    /// Parse encrypted data from a byte slice
197
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, EncryptedDataError> {
61✔
198
        if bytes.len() < STATIC_ENCRYPTED_DATA_SIZE_TOTAL {
61✔
199
            return Err(EncryptedDataError::IncorrectLength(format!(
×
200
                "Expected bytes to be at least {}, got {}",
×
201
                STATIC_ENCRYPTED_DATA_SIZE_TOTAL,
×
202
                bytes.len()
×
203
            )));
×
204
        }
61✔
205
        Ok(Self {
206
            data: MaxSizeBytes::from_bytes_checked(bytes)
61✔
207
                .ok_or(EncryptedDataError::IncorrectLength("Data too long".to_string()))?,
61✔
208
        })
209
    }
61✔
210

211
    /// Get a byte vector with the encrypted data contents
212
    pub fn to_byte_vec(&self) -> Vec<u8> {
79✔
213
        self.data.clone().into()
79✔
214
    }
79✔
215

216
    /// Get a byte slice with the encrypted data contents
217
    pub fn as_bytes(&self) -> &[u8] {
601✔
218
        &self.data
601✔
219
    }
601✔
220

221
    /// Consumes self and returns the encrypted data as a byte vector
222
    pub fn into_vec(self) -> Vec<u8> {
×
223
        self.data.into_vec()
×
224
    }
×
225

226
    /// Accessor method for the encrypted data hex display
227
    pub fn hex_display(&self, full: bool) -> String {
×
228
        if full {
×
229
            self.to_hex()
×
230
        } else {
231
            let encrypted_data_hex = self.to_hex();
×
232
            if encrypted_data_hex.len() > 2 * DISPLAY_CUTOFF {
×
233
                format!(
×
234
                    "Some({}..{})",
×
235
                    &encrypted_data_hex[0..DISPLAY_CUTOFF],
×
236
                    &encrypted_data_hex[encrypted_data_hex.len() - DISPLAY_CUTOFF..encrypted_data_hex.len()]
×
237
                )
238
            } else {
239
                encrypted_data_hex
×
240
            }
241
        }
242
    }
×
243

244
    /// Returns the size of the payment id
245
    pub fn get_payment_id_size(&self) -> usize {
325✔
246
        // the length should always at least be the static total size, the extra len is the payment id
247
        self.data.len().saturating_sub(STATIC_ENCRYPTED_DATA_SIZE_TOTAL)
325✔
248
    }
325✔
249
}
250

251
impl Hex for EncryptedData {
252
    fn from_hex(hex: &str) -> Result<Self, HexError> {
×
253
        let v = from_hex(hex)?;
×
254
        Self::from_bytes(&v).map_err(|_| HexError::HexConversionError {})
×
255
    }
×
256

257
    fn to_hex(&self) -> String {
×
258
        to_hex(&self.to_byte_vec())
×
259
    }
×
260
}
261
impl Default for EncryptedData {
262
    fn default() -> Self {
1,017✔
263
        Self {
1,017✔
264
            data: MaxSizeBytes::try_from(vec![0; STATIC_ENCRYPTED_DATA_SIZE_TOTAL])
1,017✔
265
                .expect("This will always be less then the max length"),
1,017✔
266
        }
1,017✔
267
    }
1,017✔
268
}
269
// EncryptedOpenings errors
270
#[derive(Debug, Error)]
271
pub enum EncryptedDataError {
272
    #[error("Encryption failed: {0}")]
273
    EncryptionFailed(Error),
274
    #[error("Conversion failed: {0}")]
275
    ByteArrayError(String),
276
    #[error("Incorrect length: {0}")]
277
    IncorrectLength(String),
278
}
279

280
impl From<ByteArrayError> for EncryptedDataError {
281
    fn from(e: ByteArrayError) -> Self {
×
282
        EncryptedDataError::ByteArrayError(e.to_string())
×
283
    }
×
284
}
285

286
// Chacha error is not StdError compatible
287
impl From<Error> for EncryptedDataError {
UNCOV
288
    fn from(err: Error) -> Self {
×
UNCOV
289
        Self::EncryptionFailed(err)
×
UNCOV
290
    }
×
291
}
292

293
// Generate a ChaCha20-Poly1305 key from a private key and commitment using Blake2b
294
fn kdf_aead(encryption_key: &PrivateKey, commitment: &CompressedCommitment) -> EncryptedDataKey {
1,311✔
295
    let mut aead_key = EncryptedDataKey::from(SafeArray::default());
1,311✔
296
    DomainSeparatedHasher::<Blake2b<U32>, TransactionSecureNonceKdfDomain>::new_with_label("encrypted_value_and_mask")
1,311✔
297
        .chain(encryption_key.as_bytes())
1,311✔
298
        .chain(commitment.as_bytes())
1,311✔
299
        .finalize_into(GenericArray::from_mut_slice(aead_key.reveal_mut()));
1,311✔
300

301
    aead_key
1,311✔
302
}
1,311✔
303

304
#[cfg(test)]
305
mod test {
306
    #![allow(clippy::indexing_slicing)]
307
    use static_assertions::const_assert;
308
    use tari_common_types::{
309
        tari_address::{TARI_ADDRESS_INTERNAL_DUAL_SIZE, TARI_ADDRESS_INTERNAL_SINGLE_SIZE},
310
        types::CommitmentFactory,
311
    };
312
    use tari_crypto::commitment::HomomorphicCommitmentFactory;
313

314
    use super::*;
315

316
    #[test]
UNCOV
317
    fn test_premine() {
×
UNCOV
318
        let id = 999u64;
×
UNCOV
319
        let value = 123456;
×
UNCOV
320
        let mask = PrivateKey::default();
×
UNCOV
321
        let commitment =
×
UNCOV
322
            CompressedCommitment::from_commitment(CommitmentFactory::default().commit(&mask, &PrivateKey::from(value)));
×
UNCOV
323
        let encryption_key = PrivateKey::random(&mut OsRng);
×
UNCOV
324
        let amount = MicroMinotari::from(value);
×
UNCOV
325
        let encrypted_data = {
×
UNCOV
326
            let mut bytes = Zeroizing::new(vec![0; SIZE_VALUE + SIZE_MASK + SIZE_VALUE]);
×
UNCOV
327
            bytes[..SIZE_VALUE].copy_from_slice(value.to_le_bytes().as_ref());
×
UNCOV
328
            bytes[SIZE_VALUE..SIZE_VALUE + SIZE_MASK].copy_from_slice(mask.as_bytes());
×
UNCOV
329
            bytes[SIZE_VALUE + SIZE_MASK..].copy_from_slice(&id.to_le_bytes().to_vec());
×
330

331
            // Produce a secure random nonce
UNCOV
332
            let nonce = XChaCha20Poly1305::generate_nonce(&mut OsRng);
×
333

334
            // Set up the AEAD
UNCOV
335
            let aead_key = kdf_aead(&encryption_key, &commitment);
×
UNCOV
336
            let cipher = XChaCha20Poly1305::new(GenericArray::from_slice(aead_key.reveal()));
×
337

338
            // Encrypt in place
UNCOV
339
            let tag = cipher
×
UNCOV
340
                .encrypt_in_place_detached(&nonce, ENCRYPTED_DATA_AAD, bytes.as_mut_slice())
×
UNCOV
341
                .unwrap();
×
342

343
            // Put everything together: nonce, ciphertext, tag
UNCOV
344
            let mut data = vec![0; STATIC_ENCRYPTED_DATA_SIZE_TOTAL + SIZE_VALUE];
×
UNCOV
345
            data[..SIZE_TAG].copy_from_slice(&tag);
×
UNCOV
346
            data[SIZE_TAG..SIZE_TAG + SIZE_NONCE].copy_from_slice(&nonce);
×
UNCOV
347
            data[SIZE_TAG + SIZE_NONCE..SIZE_TAG + SIZE_NONCE + SIZE_VALUE + SIZE_MASK + SIZE_VALUE]
×
UNCOV
348
                .copy_from_slice(bytes.as_slice());
×
349
            EncryptedData {
UNCOV
350
                data: MaxSizeBytes::try_from(data)
×
UNCOV
351
                    .map_err(|_| EncryptedDataError::IncorrectLength("Data too long".to_string()))
×
UNCOV
352
                    .unwrap(),
×
353
            }
354
        };
UNCOV
355
        let (decrypted_value, decrypted_mask, decrypted_payment_id) =
×
UNCOV
356
            EncryptedData::decrypt_data(&encryption_key, &commitment, &encrypted_data).unwrap();
×
UNCOV
357
        assert_eq!(amount, decrypted_value);
×
UNCOV
358
        assert_eq!(mask, decrypted_mask);
×
UNCOV
359
        if decrypted_payment_id.is_open() {
×
UNCOV
360
            let data = decrypted_payment_id.get_payment_id();
×
UNCOV
361
            let bytes: [u8; SIZE_VALUE] = data.try_into().unwrap();
×
UNCOV
362
            let v = u64::from_le_bytes(bytes);
×
UNCOV
363
            assert_eq!(v, id);
×
364
        } else {
365
            panic!("Expected PaymentId::Open");
×
366
        }
UNCOV
367
    }
×
368

369
    #[test]
UNCOV
370
    fn address_sizes_increase_as_expected() {
×
371
        const_assert!(SIZE_VALUE < SIZE_U256);
372
        const_assert!(SIZE_U256 < TARI_ADDRESS_INTERNAL_SINGLE_SIZE);
373
        const_assert!(TARI_ADDRESS_INTERNAL_SINGLE_SIZE < TARI_ADDRESS_INTERNAL_DUAL_SIZE);
UNCOV
374
    }
×
375
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc