Merge branch 'schouhy/add-signatures-to-transactions' into Pravdyvy/state-transition-token-transfer

This commit is contained in:
Oleksandr Pravdyvyi 2025-07-22 12:27:35 +03:00
commit 3eee533a17
No known key found for this signature in database
GPG Key ID: 9F8955C63C443871
18 changed files with 655 additions and 525 deletions

12
Cargo.lock generated
View File

@ -996,6 +996,7 @@ dependencies = [
"anyhow",
"elliptic-curve",
"hex",
"k256",
"log",
"reqwest 0.11.27",
"risc0-zkvm",
@ -1246,6 +1247,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
dependencies = [
"const-oid",
"pem-rfc7468",
"zeroize",
]
@ -1485,6 +1487,7 @@ dependencies = [
"ff",
"generic-array",
"group",
"pem-rfc7468",
"pkcs8",
"rand_core 0.6.4",
"sec1",
@ -3195,6 +3198,15 @@ version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19b17cddbe7ec3f8bc800887bab5e717348c95ea2ca0b1bf0837fb964dc67099"
[[package]]
name = "pem-rfc7468"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412"
dependencies = [
"base64ct",
]
[[package]]
name = "percent-encoding"
version = "2.3.1"

View File

@ -55,7 +55,7 @@ features = ["std", "std_rng", "getrandom"]
version = "0.8.5"
[workspace.dependencies.k256]
features = ["ecdsa-core", "arithmetic", "expose-field", "serde"]
features = ["ecdsa-core", "arithmetic", "expose-field", "serde", "pem"]
version = "0.13.4"
[workspace.dependencies.elliptic-curve]

View File

@ -2,12 +2,14 @@ use aes_gcm::{aead::Aead, Aes256Gcm, KeyInit};
use common::merkle_tree_public::TreeHashType;
use constants_types::{CipherText, Nonce};
use elliptic_curve::point::AffineCoordinates;
use k256::AffinePoint;
use k256::{ecdsa::SigningKey, AffinePoint, FieldBytes};
use log::info;
use rand::{rngs::OsRng, RngCore};
use secret_holders::{SeedHolder, TopSecretKeyHolder, UTXOSecretKeyHolder};
use serde::{Deserialize, Serialize};
use crate::account_core::PublicKey;
pub type PublicAccountSigningKey = [u8; 32];
pub mod constants_types;
pub mod ephemeral_key_holder;
@ -20,6 +22,7 @@ pub struct AddressKeyHolder {
#[allow(dead_code)]
top_secret_key_holder: TopSecretKeyHolder,
pub utxo_secret_key_holder: UTXOSecretKeyHolder,
pub_account_signing_key: PublicAccountSigningKey,
pub address: TreeHashType,
pub nullifer_public_key: PublicKey,
pub viewing_public_key: PublicKey,
@ -38,15 +41,29 @@ impl AddressKeyHolder {
let nullifer_public_key = utxo_secret_key_holder.generate_nullifier_public_key();
let viewing_public_key = utxo_secret_key_holder.generate_viewing_public_key();
let pub_account_signing_key = {
let mut bytes = [0; 32];
OsRng.fill_bytes(&mut bytes);
bytes
};
Self {
top_secret_key_holder,
utxo_secret_key_holder,
address,
nullifer_public_key,
viewing_public_key,
pub_account_signing_key,
}
}
/// Returns the signing key for public transaction signatures
pub fn get_pub_account_signing_key(&self) -> SigningKey {
let field_bytes = FieldBytes::from_slice(&self.pub_account_signing_key);
// TODO: remove unwrap
SigningKey::from_bytes(&field_bytes).unwrap()
}
pub fn calculate_shared_secret_receiver(
&self,
ephemeral_public_key_sender: AffinePoint,
@ -305,6 +322,16 @@ mod tests {
assert_eq!(decrypted_data, plaintext);
}
#[test]
fn test_get_public_account_signing_key() {
let address_key_holder = AddressKeyHolder::new_os_random();
let signing_key = address_key_holder.get_pub_account_signing_key();
assert_eq!(
signing_key.to_bytes().as_slice(),
address_key_holder.pub_account_signing_key
);
}
#[test]
fn key_generation_test() {
let seed_holder = SeedHolder::new_os_random();

View File

@ -10,6 +10,7 @@ serde_json.workspace = true
serde.workspace = true
reqwest.workspace = true
risc0-zkvm = { git = "https://github.com/risc0/risc0.git", branch = "release-2.3" }
k256.workspace = true
rs_merkle.workspace = true
sha2.workspace = true

View File

@ -89,3 +89,9 @@ impl ExecutionFailureKind {
Self::DBError(err)
}
}
#[derive(Debug, thiserror::Error)]
pub enum TransactionSignatureError {
#[error("invalid signature for transaction body")]
InvalidSignature,
}

View File

@ -140,7 +140,7 @@ impl<Leav: TreeLeavItem + Clone> HashStorageMerkleTree<Leav> {
}
}
pub fn add_tx(&mut self, tx: Leav) {
pub fn add_tx(&mut self, tx: &Leav) {
let last = self.leaves.len();
self.leaves.insert(last, tx.clone());
@ -267,7 +267,7 @@ mod tests {
let mut tree = HashStorageMerkleTree::new(vec![tx1.clone()]);
tree.add_tx(tx2.clone());
tree.add_tx(&tx2);
assert_eq!(tree.leaves.len(), 2);
assert_eq!(tree.get_tx(tx2.hash()), Some(&tx2));
}

View File

@ -8,7 +8,7 @@ pub trait TreeLeavItem {
impl TreeLeavItem for Transaction {
fn hash(&self) -> TreeHashType {
self.hash
self.body().hash()
}
}

View File

@ -1,6 +1,11 @@
use k256::ecdsa::{
signature::{Signer, Verifier},
Signature, SigningKey, VerifyingKey,
};
use log::info;
use secp256k1_zkp::{PedersenCommitment, Tweak};
use serde::{Deserialize, Serialize};
use sha2::{digest::FixedOutput, Digest};
use crate::merkle_tree_public::TreeHashType;
@ -11,11 +16,13 @@ use elliptic_curve::{
};
use sha2::digest::typenum::{UInt, UTerm};
use crate::TransactionSignatureError;
pub type CipherText = Vec<u8>;
pub type Nonce = GenericArray<u8, UInt<UInt<UInt<UInt<UTerm, B1>, B1>, B0>, B0>>;
pub type Tag = u8;
#[derive(Debug, Serialize, Deserialize, Clone, Copy)]
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
pub enum TxKind {
Public,
Private,
@ -23,10 +30,9 @@ pub enum TxKind {
Deshielded,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
///General transaction object
pub struct Transaction {
pub hash: TreeHashType,
pub struct TransactionBody {
pub tx_kind: TxKind,
///Tx input data (public part)
pub execution_input: Vec<u8>,
@ -58,70 +64,6 @@ pub struct Transaction {
pub state_changes: (serde_json::Value, usize),
}
#[derive(Debug, Serialize, Deserialize, Clone)]
///General transaction object
pub struct TransactionPayload {
pub tx_kind: TxKind,
///Tx input data (public part)
pub execution_input: Vec<u8>,
///Tx output data (public_part)
pub execution_output: Vec<u8>,
///Tx input utxo commitments
pub utxo_commitments_spent_hashes: Vec<TreeHashType>,
///Tx output utxo commitments
pub utxo_commitments_created_hashes: Vec<TreeHashType>,
///Tx output nullifiers
pub nullifier_created_hashes: Vec<TreeHashType>,
///Execution proof (private part)
pub execution_proof_private: String,
///Encoded blobs of data
pub encoded_data: Vec<(CipherText, Vec<u8>, Tag)>,
///Transaction senders ephemeral pub key
pub ephemeral_pub_key: Vec<u8>,
///Public (Pedersen) commitment
pub commitment: Vec<PedersenCommitment>,
///tweak
pub tweak: Tweak,
///secret_r
pub secret_r: [u8; 32],
///Hex-encoded address of a smart contract account called
pub sc_addr: String,
///Recorded changes in state of smart contract
///
/// First value represents vector of changes, second is new length of a state
pub state_changes: (serde_json::Value, usize),
}
impl From<TransactionPayload> for Transaction {
fn from(value: TransactionPayload) -> Self {
let raw_data = serde_json::to_vec(&value).unwrap();
let mut hasher = sha2::Sha256::new();
hasher.update(&raw_data);
let hash = <TreeHashType>::from(hasher.finalize_fixed());
Self {
hash,
tx_kind: value.tx_kind,
execution_input: value.execution_input,
execution_output: value.execution_output,
utxo_commitments_spent_hashes: value.utxo_commitments_spent_hashes,
utxo_commitments_created_hashes: value.utxo_commitments_created_hashes,
nullifier_created_hashes: value.nullifier_created_hashes,
execution_proof_private: value.execution_proof_private,
encoded_data: value.encoded_data,
ephemeral_pub_key: value.ephemeral_pub_key,
commitment: value.commitment,
tweak: value.tweak,
secret_r: value.secret_r,
sc_addr: value.sc_addr,
state_changes: value.state_changes,
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct MintMoneyPublicTx {
pub acc: [u8; 32],
@ -209,15 +151,30 @@ impl ActionData {
.into_iter()
.map(|owned_utxo| owned_utxo.into())
.collect();
format!("Published utxos {:?}", pub_own_utxo)
format!("Published utxos {pub_own_utxo:?}")
}
}
}
}
impl Transaction {
impl TransactionBody {
/// Computes and returns the SHA-256 hash of the JSON-serialized representation of `self`.
pub fn hash(&self) -> TreeHashType {
let bytes_to_hash = self.to_bytes();
let mut hasher = sha2::Sha256::new();
hasher.update(&bytes_to_hash);
TreeHashType::from(hasher.finalize_fixed())
}
fn to_bytes(&self) -> Vec<u8> {
// TODO: Remove `unwrap` by implementing a `to_bytes` method
// that deterministically encodes all transaction fields to bytes
// and guarantees serialization will succeed.
serde_json::to_vec(&self).unwrap()
}
pub fn log(&self) {
info!("Transaction hash is {:?}", hex::encode(self.hash));
info!("Transaction hash is {:?}", hex::encode(self.hash()));
info!("Transaction tx_kind is {:?}", self.tx_kind);
info!("Transaction execution_input is {:?}", {
if let Ok(action) = serde_json::from_slice::<ActionData>(&self.execution_input) {
@ -237,21 +194,21 @@ impl Transaction {
"Transaction utxo_commitments_spent_hashes is {:?}",
self.utxo_commitments_spent_hashes
.iter()
.map(|val| hex::encode(val.clone()))
.map(|val| hex::encode(*val))
.collect::<Vec<_>>()
);
info!(
"Transaction utxo_commitments_created_hashes is {:?}",
self.utxo_commitments_created_hashes
.iter()
.map(|val| hex::encode(val.clone()))
.map(|val| hex::encode(*val))
.collect::<Vec<_>>()
);
info!(
"Transaction nullifier_created_hashes is {:?}",
self.nullifier_created_hashes
.iter()
.map(|val| hex::encode(val.clone()))
.map(|val| hex::encode(*val))
.collect::<Vec<_>>()
);
info!(
@ -267,3 +224,198 @@ impl Transaction {
);
}
}
type TransactionHash = [u8; 32];
pub type TransactionSignature = Signature;
pub type SignaturePublicKey = VerifyingKey;
pub type SignaturePrivateKey = SigningKey;
/// A container for a transaction body with a signature.
/// Meant to be sent through the network to the sequencer
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct Transaction {
body: TransactionBody,
signature: TransactionSignature,
public_key: VerifyingKey,
}
impl Transaction {
/// Returns a new transaction signed with the provided `private_key`.
/// The signature is generated over the hash of the body as computed by `body.hash()`
pub fn new(body: TransactionBody, private_key: SigningKey) -> Transaction {
let signature: TransactionSignature = private_key.sign(&body.to_bytes());
let public_key = VerifyingKey::from(&private_key);
Self {
body,
signature,
public_key,
}
}
/// Converts the transaction into an `AuthenticatedTransaction` by verifying its signature.
/// Returns an error if the signature verification fails.
pub fn into_authenticated(self) -> Result<AuthenticatedTransaction, TransactionSignatureError> {
let hash = self.body.hash();
self.public_key
.verify(&self.body.to_bytes(), &self.signature)
.map_err(|_| TransactionSignatureError::InvalidSignature)?;
Ok(AuthenticatedTransaction {
hash,
transaction: self,
})
}
/// Returns the body of the transaction
pub fn body(&self) -> &TransactionBody {
&self.body
}
}
/// A transaction with a valid signature over the hash of its body.
/// Can only be constructed from an `Transaction`
/// if the signature is valid
#[derive(Debug, Clone)]
pub struct AuthenticatedTransaction {
hash: TransactionHash,
transaction: Transaction,
}
impl AuthenticatedTransaction {
/// Returns the underlying transaction
pub fn transaction(&self) -> &Transaction {
&self.transaction
}
/// Returns the precomputed hash over the body of the transaction
pub fn hash(&self) -> &TransactionHash {
&self.hash
}
}
#[cfg(test)]
mod tests {
use super::*;
use k256::{ecdsa::signature::Signer, FieldBytes};
use secp256k1_zkp::{constants::SECRET_KEY_SIZE, Tweak};
use sha2::{digest::FixedOutput, Digest};
use crate::{
merkle_tree_public::TreeHashType,
transaction::{Transaction, TransactionBody, TxKind},
};
fn test_transaction_body() -> TransactionBody {
TransactionBody {
tx_kind: TxKind::Public,
execution_input: vec![1, 2, 3, 4],
execution_output: vec![5, 6, 7, 8],
utxo_commitments_spent_hashes: vec![[9; 32], [10; 32], [11; 32], [12; 32]],
utxo_commitments_created_hashes: vec![[13; 32]],
nullifier_created_hashes: vec![[0; 32], [1; 32], [2; 32], [3; 32]],
execution_proof_private: "loremipsum".to_string(),
encoded_data: vec![(vec![255, 255, 255], vec![254, 254, 254], 1)],
ephemeral_pub_key: vec![5; 32],
commitment: vec![],
tweak: Tweak::from_slice(&[7; SECRET_KEY_SIZE]).unwrap(),
secret_r: [8; 32],
sc_addr: "someAddress".to_string(),
state_changes: (serde_json::Value::Null, 10),
}
}
fn test_transaction() -> Transaction {
let body = test_transaction_body();
let key_bytes = FieldBytes::from_slice(&[37; 32]);
let private_key: SigningKey = SigningKey::from_bytes(key_bytes).unwrap();
Transaction::new(body, private_key)
}
#[test]
fn test_transaction_hash_is_sha256_of_json_bytes() {
let body = test_transaction_body();
let expected_hash = {
let data = serde_json::to_vec(&body).unwrap();
let mut hasher = sha2::Sha256::new();
hasher.update(&data);
TreeHashType::from(hasher.finalize_fixed())
};
let hash = body.hash();
assert_eq!(expected_hash, hash);
}
#[test]
fn test_transaction_constructor() {
let body = test_transaction_body();
let key_bytes = FieldBytes::from_slice(&[37; 32]);
let private_key: SigningKey = SigningKey::from_bytes(key_bytes).unwrap();
let transaction = Transaction::new(body.clone(), private_key.clone());
assert_eq!(
transaction.public_key,
SignaturePublicKey::from(&private_key)
);
assert_eq!(transaction.body, body);
}
#[test]
fn test_transaction_body_getter() {
let body = test_transaction_body();
let key_bytes = FieldBytes::from_slice(&[37; 32]);
let private_key: SigningKey = SigningKey::from_bytes(key_bytes).unwrap();
let transaction = Transaction::new(body.clone(), private_key.clone());
assert_eq!(transaction.body(), &body);
}
#[test]
fn test_into_authenticated_succeeds_for_valid_signature() {
let transaction = test_transaction();
let authenticated_tx = transaction.clone().into_authenticated().unwrap();
let signature = authenticated_tx.transaction().signature;
let hash = authenticated_tx.hash();
assert_eq!(authenticated_tx.transaction(), &transaction);
assert_eq!(hash, &transaction.body.hash());
assert!(authenticated_tx
.transaction()
.public_key
.verify(&transaction.body.to_bytes(), &signature)
.is_ok());
}
#[test]
fn test_into_authenticated_fails_for_invalid_signature() {
let body = test_transaction_body();
let key_bytes = FieldBytes::from_slice(&[37; 32]);
let private_key: SigningKey = SigningKey::from_bytes(key_bytes).unwrap();
let transaction = {
let mut this = Transaction::new(body, private_key.clone());
// Modify the signature to make it invalid
// We do this by changing it to the signature of something else
this.signature = private_key.sign(b"deadbeef");
this
};
matches!(
transaction.into_authenticated(),
Err(TransactionSignatureError::InvalidSignature)
);
}
#[test]
fn test_authenticated_transaction_getter() {
let transaction = test_transaction();
let authenticated_tx = transaction.clone().into_authenticated().unwrap();
assert_eq!(authenticated_tx.transaction(), &transaction);
}
#[test]
fn test_authenticated_transaction_hash_getter() {
let transaction = test_transaction();
let authenticated_tx = transaction.clone().into_authenticated().unwrap();
assert_eq!(authenticated_tx.hash(), &transaction.body.hash());
}
}

View File

@ -127,8 +127,9 @@ impl NodeChainStore {
let block_id = block.block_id;
for tx in &block.transactions {
if !tx.execution_input.is_empty() {
let public_action = serde_json::from_slice::<ActionData>(&tx.execution_input);
if !tx.body().execution_input.is_empty() {
let public_action =
serde_json::from_slice::<ActionData>(&tx.body().execution_input);
if let Ok(public_action) = public_action {
match public_action {
@ -176,24 +177,25 @@ impl NodeChainStore {
}
self.utxo_commitments_store.add_tx_multiple(
tx.utxo_commitments_created_hashes
tx.body()
.utxo_commitments_created_hashes
.clone()
.into_iter()
.map(|hash| UTXOCommitment { hash })
.collect(),
);
for nullifier in tx.nullifier_created_hashes.iter() {
for nullifier in tx.body().nullifier_created_hashes.iter() {
self.nullifier_store.insert(UTXONullifier {
utxo_hash: *nullifier,
});
}
if !tx.encoded_data.is_empty() {
if !tx.body().encoded_data.is_empty() {
let ephemeral_public_key_sender =
serde_json::from_slice::<AffinePoint>(&tx.ephemeral_pub_key)?;
serde_json::from_slice::<AffinePoint>(&tx.body().ephemeral_pub_key)?;
for (ciphertext, nonce, tag) in tx.encoded_data.clone() {
for (ciphertext, nonce, tag) in tx.body().encoded_data.clone() {
let slice = nonce.as_slice();
let nonce =
accounts::key_management::constants_types::Nonce::clone_from_slice(slice);
@ -218,7 +220,7 @@ impl NodeChainStore {
}
}
self.pub_tx_store.add_tx(tx.clone());
self.pub_tx_store.add_tx(tx);
}
self.block_store.put_block_at_id(block)?;
@ -298,7 +300,7 @@ mod tests {
use accounts::account_core::Account;
use common::block::{Block, Data};
use common::merkle_tree_public::TreeHashType;
use common::transaction::{Transaction, TxKind};
use common::transaction::{SignaturePrivateKey, Transaction, TransactionBody, TxKind};
use secp256k1_zkp::Tweak;
use std::path::PathBuf;
use tempfile::tempdir;
@ -315,16 +317,13 @@ mod tests {
}
fn create_dummy_transaction(
hash: TreeHashType,
// execution_input: Vec<u8>,
nullifier_created_hashes: Vec<[u8; 32]>,
utxo_commitments_spent_hashes: Vec<[u8; 32]>,
utxo_commitments_created_hashes: Vec<[u8; 32]>,
) -> Transaction {
let mut rng = rand::thread_rng();
Transaction {
hash,
let body = TransactionBody {
tx_kind: TxKind::Private,
execution_input: vec![],
execution_output: vec![],
@ -339,7 +338,8 @@ mod tests {
secret_r: [0; 32],
sc_addr: "sc_addr".to_string(),
state_changes: (serde_json::Value::Null, 0),
}
};
Transaction::new(body, SignaturePrivateKey::random(&mut rng))
}
fn create_sample_block(block_id: u64, prev_block_id: u64) -> Block {
@ -435,8 +435,7 @@ mod tests {
store
.utxo_commitments_store
.add_tx_multiple(vec![UTXOCommitment { hash: [3u8; 32] }]);
store.pub_tx_store.add_tx(create_dummy_transaction(
[12; 32],
store.pub_tx_store.add_tx(&create_dummy_transaction(
vec![[9; 32]],
vec![[7; 32]],
vec![[8; 32]],

View File

@ -3,7 +3,7 @@ use std::sync::{
Arc,
};
use common::{public_transfer_receipts::PublicNativeTokenSend, ExecutionFailureKind};
use common::{transaction::Transaction, ExecutionFailureKind};
use accounts::{
account_core::{Account, AccountAddress},
@ -11,7 +11,7 @@ use accounts::{
};
use anyhow::Result;
use chain_storage::NodeChainStore;
use common::transaction::{Transaction, TransactionPayload, TxKind};
use common::transaction::{TransactionBody, TxKind};
use config::NodeConfig;
use log::info;
use sc_core::proofs_circuits::{
@ -247,31 +247,30 @@ impl NodeCore {
let vec_public_info: Vec<u64> = vec_values_u64.into_iter().flatten().collect();
let (tweak, secret_r, commitment) = pedersen_commitment_vec(vec_public_info);
let transaction_body = TransactionBody {
tx_kind: TxKind::Private,
execution_input: vec![],
execution_output: vec![],
utxo_commitments_spent_hashes: vec![],
utxo_commitments_created_hashes: comm
.into_iter()
.map(|hash_data| hash_data.try_into().unwrap())
.collect(),
nullifier_created_hashes: vec![],
execution_proof_private: sc_core::transaction_payloads_tools::encode_receipt(receipt)
.unwrap(),
encoded_data: vec![(encoded_data.0, encoded_data.1.to_vec(), tag)],
ephemeral_pub_key: eph_pub_key.to_vec(),
commitment,
tweak,
secret_r,
sc_addr,
state_changes,
};
let key_to_sign_transaction = account.key_holder.get_pub_account_signing_key();
Ok((
TransactionPayload {
tx_kind: TxKind::Private,
execution_input: vec![],
execution_output: vec![],
utxo_commitments_spent_hashes: vec![],
utxo_commitments_created_hashes: comm
.into_iter()
.map(|hash_data| hash_data.try_into().unwrap())
.collect(),
nullifier_created_hashes: vec![],
execution_proof_private: sc_core::transaction_payloads_tools::encode_receipt(
receipt,
)
.unwrap(),
encoded_data: vec![(encoded_data.0, encoded_data.1.to_vec(), tag)],
ephemeral_pub_key: eph_pub_key.to_vec(),
commitment,
tweak,
secret_r,
sc_addr,
state_changes,
}
.into(),
Transaction::new(transaction_body, key_to_sign_transaction),
result_hash,
))
}
@ -345,30 +344,30 @@ impl NodeCore {
let (tweak, secret_r, commitment) = pedersen_commitment_vec(vec_public_info);
Ok((
TransactionPayload {
tx_kind: TxKind::Private,
execution_input: vec![],
execution_output: vec![],
utxo_commitments_spent_hashes: vec![],
utxo_commitments_created_hashes: comm
.into_iter()
.map(|hash_data| hash_data.try_into().unwrap())
.collect(),
nullifier_created_hashes: vec![],
execution_proof_private: sc_core::transaction_payloads_tools::encode_receipt(
receipt,
)
let transaction_body = TransactionBody {
tx_kind: TxKind::Private,
execution_input: vec![],
execution_output: vec![],
utxo_commitments_spent_hashes: vec![],
utxo_commitments_created_hashes: comm
.into_iter()
.map(|hash_data| hash_data.try_into().unwrap())
.collect(),
nullifier_created_hashes: vec![],
execution_proof_private: sc_core::transaction_payloads_tools::encode_receipt(receipt)
.unwrap(),
encoded_data,
ephemeral_pub_key: eph_pub_key.to_vec(),
commitment,
tweak,
secret_r,
sc_addr,
state_changes,
}
.into(),
encoded_data,
ephemeral_pub_key: eph_pub_key.to_vec(),
commitment,
tweak,
secret_r,
sc_addr,
state_changes,
};
let key_to_sign_transaction = account.key_holder.get_pub_account_signing_key();
Ok((
Transaction::new(transaction_body, key_to_sign_transaction),
result_hashes,
))
}
@ -461,30 +460,31 @@ impl NodeCore {
let (tweak, secret_r, commitment) = pedersen_commitment_vec(vec_public_info);
Ok((
TransactionPayload {
tx_kind: TxKind::Private,
execution_input: vec![],
execution_output: vec![],
utxo_commitments_spent_hashes: vec![commitment_in],
utxo_commitments_created_hashes: commitments
.into_iter()
.map(|hash_data| hash_data.try_into().unwrap())
.collect(),
nullifier_created_hashes: vec![nullifier.try_into().unwrap()],
execution_proof_private: sc_core::transaction_payloads_tools::encode_receipt(
receipt,
)
let transaction_body = TransactionBody {
tx_kind: TxKind::Private,
execution_input: vec![],
execution_output: vec![],
utxo_commitments_spent_hashes: vec![commitment_in],
utxo_commitments_created_hashes: commitments
.into_iter()
.map(|hash_data| hash_data.try_into().unwrap())
.collect(),
nullifier_created_hashes: vec![nullifier.try_into().unwrap()],
execution_proof_private: sc_core::transaction_payloads_tools::encode_receipt(receipt)
.unwrap(),
encoded_data,
ephemeral_pub_key: eph_pub_key.to_vec(),
commitment,
tweak,
secret_r,
sc_addr,
state_changes,
}
.into(),
encoded_data,
ephemeral_pub_key: eph_pub_key.to_vec(),
commitment,
tweak,
secret_r,
sc_addr,
state_changes,
};
let key_to_sign_transaction = account.key_holder.get_pub_account_signing_key();
Ok((
Transaction::new(transaction_body, key_to_sign_transaction),
utxo_hashes,
))
}
@ -606,30 +606,31 @@ impl NodeCore {
let (tweak, secret_r, commitment) = pedersen_commitment_vec(vec_public_info);
Ok((
TransactionPayload {
tx_kind: TxKind::Private,
execution_input: vec![],
execution_output: vec![],
utxo_commitments_spent_hashes: commitments_in,
utxo_commitments_created_hashes: commitments
.into_iter()
.map(|hash_data| hash_data.try_into().unwrap())
.collect(),
nullifier_created_hashes: nullifiers,
execution_proof_private: sc_core::transaction_payloads_tools::encode_receipt(
receipt,
)
let transaction_body = TransactionBody {
tx_kind: TxKind::Private,
execution_input: vec![],
execution_output: vec![],
utxo_commitments_spent_hashes: commitments_in,
utxo_commitments_created_hashes: commitments
.into_iter()
.map(|hash_data| hash_data.try_into().unwrap())
.collect(),
nullifier_created_hashes: nullifiers,
execution_proof_private: sc_core::transaction_payloads_tools::encode_receipt(receipt)
.unwrap(),
encoded_data,
ephemeral_pub_key: eph_pub_key.to_vec(),
commitment,
tweak,
secret_r,
sc_addr,
state_changes,
}
.into(),
encoded_data,
ephemeral_pub_key: eph_pub_key.to_vec(),
commitment,
tweak,
secret_r,
sc_addr,
state_changes,
};
let key_to_sign_transaction = account.key_holder.get_pub_account_signing_key();
Ok((
Transaction::new(transaction_body, key_to_sign_transaction),
utxo_hashes_receiver,
utxo_hashes_not_spent,
))
@ -729,36 +730,37 @@ impl NodeCore {
let (tweak, secret_r, commitment) = pedersen_commitment_vec(vec_public_info);
let transaction_body = TransactionBody {
tx_kind: TxKind::Shielded,
execution_input: serde_json::to_vec(&ActionData::SendMoneyShieldedTx(
SendMoneyShieldedTx {
acc_sender: acc,
amount: balance as u128,
},
))
.unwrap(),
execution_output: vec![],
utxo_commitments_spent_hashes: vec![],
utxo_commitments_created_hashes: commitments
.into_iter()
.map(|hash_data| hash_data.try_into().unwrap())
.collect(),
nullifier_created_hashes: vec![nullifier.try_into().unwrap()],
execution_proof_private: sc_core::transaction_payloads_tools::encode_receipt(receipt)
.unwrap(),
encoded_data,
ephemeral_pub_key: eph_pub_key.to_vec(),
commitment,
tweak,
secret_r,
sc_addr,
state_changes,
};
let key_to_sign_transaction = account.key_holder.get_pub_account_signing_key();
Ok((
TransactionPayload {
tx_kind: TxKind::Shielded,
execution_input: serde_json::to_vec(&ActionData::SendMoneyShieldedTx(
SendMoneyShieldedTx {
acc_sender: acc,
amount: balance as u128,
},
))
.unwrap(),
execution_output: vec![],
utxo_commitments_spent_hashes: vec![],
utxo_commitments_created_hashes: commitments
.into_iter()
.map(|hash_data| hash_data.try_into().unwrap())
.collect(),
nullifier_created_hashes: vec![nullifier.try_into().unwrap()],
execution_proof_private: sc_core::transaction_payloads_tools::encode_receipt(
receipt,
)
.unwrap(),
encoded_data,
ephemeral_pub_key: eph_pub_key.to_vec(),
commitment,
tweak,
secret_r,
sc_addr,
state_changes,
}
.into(),
Transaction::new(transaction_body, key_to_sign_transaction),
utxo_hashes,
))
}
@ -823,7 +825,7 @@ impl NodeCore {
let (tweak, secret_r, commitment) = pedersen_commitment_vec(vec_public_info);
Ok(TransactionPayload {
let transaction_body = TransactionBody {
tx_kind: TxKind::Deshielded,
execution_input: serde_json::to_vec(&ActionData::SendMoneyDeshieldedTx(
SendMoneyDeshieldedTx {
@ -844,8 +846,11 @@ impl NodeCore {
secret_r,
sc_addr,
state_changes,
}
.into())
};
let key_to_sign_transaction = account.key_holder.get_pub_account_signing_key();
Ok(Transaction::new(transaction_body, key_to_sign_transaction))
}
pub async fn send_private_mint_tx(
@ -858,10 +863,10 @@ impl NodeCore {
let point_before_prove = std::time::Instant::now();
let (tx, utxo_hash) = self.mint_utxo_private(acc, amount).await?;
tx.log();
tx.body().log();
let point_after_prove = std::time::Instant::now();
let commitment_generated_hash = tx.utxo_commitments_created_hashes[0];
let commitment_generated_hash = tx.body().utxo_commitments_created_hashes[0];
let timedelta = (point_after_prove - point_before_prove).as_millis();
info!("Mint utxo proof spent {timedelta:?} milliseconds");
@ -886,10 +891,10 @@ impl NodeCore {
let (tx, utxo_hashes) = self
.mint_utxo_multiple_assets_private(acc, amount, number_of_assets)
.await?;
tx.log();
tx.body().log();
let point_after_prove = std::time::Instant::now();
let commitment_generated_hashes = tx.utxo_commitments_created_hashes.clone();
let commitment_generated_hashes = tx.body().utxo_commitments_created_hashes.clone();
let timedelta = (point_after_prove - point_before_prove).as_millis();
info!("Mint utxo proof spent {timedelta:?} milliseconds");
@ -901,50 +906,50 @@ impl NodeCore {
))
}
pub async fn send_public_deposit(
&self,
acc: AccountAddress,
amount: u128,
) -> Result<SendTxResponse, ExecutionFailureKind> {
//Considering proof time, needs to be done before proof
let tx_roots = self.get_roots().await;
let public_context = {
let read_guard = self.storage.read().await;
read_guard.produce_context(acc)
};
let (tweak, secret_r, commitment) = pedersen_commitment_vec(
//Will not panic, as public context is serializable
public_context.produce_u64_list_from_context().unwrap(),
);
let sc_addr = hex::encode([0; 32]);
//Sc does not change its state
let state_changes: Vec<DataBlobChangeVariant> = vec![];
let new_len = 0;
let state_changes = (serde_json::to_value(state_changes).unwrap(), new_len);
let tx: Transaction =
sc_core::transaction_payloads_tools::create_public_transaction_payload(
serde_json::to_vec(&ActionData::MintMoneyPublicTx(MintMoneyPublicTx {
acc,
amount,
}))
.unwrap(),
commitment,
tweak,
secret_r,
sc_addr,
state_changes,
)
.into();
tx.log();
Ok(self.sequencer_client.send_tx(tx, tx_roots).await?)
}
// pub async fn send_public_deposit(
// &self,
// acc: AccountAddress,
// amount: u128,
// ) -> Result<SendTxResponse, ExecutionFailureKind> {
// //Considering proof time, needs to be done before proof
// let tx_roots = self.get_roots().await;
//
// let public_context = {
// let read_guard = self.storage.read().await;
//
// read_guard.produce_context(acc)
// };
//
// let (tweak, secret_r, commitment) = pedersen_commitment_vec(
// //Will not panic, as public context is serializable
// public_context.produce_u64_list_from_context().unwrap(),
// );
//
// let sc_addr = hex::encode([0; 32]);
//
// //Sc does not change its state
// let state_changes: Vec<DataBlobChangeVariant> = vec![];
// let new_len = 0;
// let state_changes = (serde_json::to_value(state_changes).unwrap(), new_len);
//
// let tx: TransactionBody =
// sc_core::transaction_payloads_tools::create_public_transaction_payload(
// serde_json::to_vec(&ActionData::MintMoneyPublicTx(MintMoneyPublicTx {
// acc,
// amount,
// }))
// .unwrap(),
// commitment,
// tweak,
// secret_r,
// sc_addr,
// state_changes,
// )
// .into();
// tx.log();
//
// Ok(self.sequencer_client.send_tx(tx, tx_roots).await?)
// }
pub async fn send_public_native_token_transfer(
&self,
@ -1005,7 +1010,7 @@ impl NodeCore {
let (tx, utxo_hashes) = self
.transfer_utxo_private(utxo, comm_hash, receivers)
.await?;
tx.log();
tx.body().log();
let point_after_prove = std::time::Instant::now();
let timedelta = (point_after_prove - point_before_prove).as_millis();
@ -1031,7 +1036,7 @@ impl NodeCore {
let (tx, utxo_hashes_received, utxo_hashes_not_spent) = self
.transfer_utxo_multiple_assets_private(utxos, comm_hashes, number_to_send, receiver)
.await?;
tx.log();
tx.body().log();
let point_after_prove = std::time::Instant::now();
let timedelta = (point_after_prove - point_before_prove).as_millis();
@ -1057,7 +1062,7 @@ impl NodeCore {
let (tx, utxo_hashes) = self
.transfer_balance_shielded(acc, amount, receivers)
.await?;
tx.log();
tx.body().log();
let point_after_prove = std::time::Instant::now();
let timedelta = (point_after_prove - point_before_prove).as_millis();
@ -1082,7 +1087,7 @@ impl NodeCore {
let tx = self
.transfer_utxo_deshielded(utxo, comm_gen_hash, receivers)
.await?;
tx.log();
tx.body().log();
let point_after_prove = std::time::Instant::now();
let timedelta = (point_after_prove - point_before_prove).as_millis();
@ -1216,46 +1221,46 @@ impl NodeCore {
Ok(())
}
pub async fn operate_account_deposit_public(
&mut self,
acc_addr: AccountAddress,
amount: u128,
) -> Result<(), ExecutionFailureKind> {
let old_balance = {
let acc_map_read_guard = self.storage.read().await;
let acc = acc_map_read_guard.acc_map.get(&acc_addr).unwrap();
acc.balance
};
info!(
"Balance of {:?} now is {old_balance:?}",
hex::encode(acc_addr)
);
let resp = self.send_public_deposit(acc_addr, amount).await?;
info!("Response for public deposit is {resp:?}");
info!("Awaiting new blocks");
tokio::time::sleep(std::time::Duration::from_secs(BLOCK_GEN_DELAY_SECS)).await;
let new_balance = {
let acc_map_read_guard = self.storage.read().await;
let acc = acc_map_read_guard.acc_map.get(&acc_addr).unwrap();
acc.balance
};
info!(
"Balance of {:?} now is {new_balance:?}, delta is {:?}",
hex::encode(acc_addr),
new_balance - old_balance
);
Ok(())
}
// pub async fn operate_account_deposit_public(
// &mut self,
// acc_addr: AccountAddress,
// amount: u128,
// ) -> Result<(), ExecutionFailureKind> {
// let old_balance = {
// let acc_map_read_guard = self.storage.read().await;
//
// let acc = acc_map_read_guard.acc_map.get(&acc_addr).unwrap();
//
// acc.balance
// };
//
// info!(
// "Balance of {:?} now is {old_balance:?}",
// hex::encode(acc_addr)
// );
//
// let resp = self.send_public_deposit(acc_addr, amount).await?;
// info!("Response for public deposit is {resp:?}");
//
// info!("Awaiting new blocks");
// tokio::time::sleep(std::time::Duration::from_secs(BLOCK_GEN_DELAY_SECS)).await;
//
// let new_balance = {
// let acc_map_read_guard = self.storage.read().await;
//
// let acc = acc_map_read_guard.acc_map.get(&acc_addr).unwrap();
//
// acc.balance
// };
//
// info!(
// "Balance of {:?} now is {new_balance:?}, delta is {:?}",
// hex::encode(acc_addr),
// new_balance - old_balance
// );
//
// Ok(())
// }
pub async fn operate_account_send_shielded_one_receiver(
&mut self,
@ -1507,31 +1512,31 @@ impl NodeCore {
let (tweak, secret_r, commitment) = pedersen_commitment_vec(vec_public_info);
Ok((
TransactionPayload {
tx_kind: TxKind::Shielded,
execution_input: vec![],
execution_output: serde_json::to_vec(&publication).unwrap(),
utxo_commitments_spent_hashes: vec![commitment_in],
utxo_commitments_created_hashes: commitments
.clone()
.into_iter()
.map(|hash_data| hash_data.try_into().unwrap())
.collect(),
nullifier_created_hashes: vec![nullifier.try_into().unwrap()],
execution_proof_private: sc_core::transaction_payloads_tools::encode_receipt(
receipt,
)
let transaction_body = TransactionBody {
tx_kind: TxKind::Shielded,
execution_input: vec![],
execution_output: serde_json::to_vec(&publication).unwrap(),
utxo_commitments_spent_hashes: vec![commitment_in],
utxo_commitments_created_hashes: commitments
.clone()
.into_iter()
.map(|hash_data| hash_data.try_into().unwrap())
.collect(),
nullifier_created_hashes: vec![nullifier.try_into().unwrap()],
execution_proof_private: sc_core::transaction_payloads_tools::encode_receipt(receipt)
.unwrap(),
encoded_data,
ephemeral_pub_key: eph_pub_key.to_vec(),
commitment,
tweak,
secret_r,
sc_addr,
state_changes,
}
.into(),
encoded_data,
ephemeral_pub_key: eph_pub_key.to_vec(),
commitment,
tweak,
secret_r,
sc_addr,
state_changes,
};
let key_to_sign_transaction = account.key_holder.get_pub_account_signing_key();
Ok((
Transaction::new(transaction_body, key_to_sign_transaction),
utxo_hashes,
))
}
@ -1551,13 +1556,13 @@ impl NodeCore {
let (tx, utxo_hashes) = self
.split_utxo(utxo, comm_hash, receivers, visibility_list)
.await?;
tx.log();
tx.body().log();
let point_after_prove = std::time::Instant::now();
let timedelta = (point_after_prove - point_before_prove).as_millis();
info!("Send private utxo proof spent {timedelta:?} milliseconds");
let commitments = tx.utxo_commitments_created_hashes.clone();
let commitments = tx.body().utxo_commitments_created_hashes.clone();
Ok((
self.sequencer_client.send_tx(tx, tx_roots).await?,
@ -1631,20 +1636,8 @@ impl NodeCore {
Ok(())
}
///Deposit balance, make it private
pub async fn subscenario_2(&mut self) -> Result<(), ExecutionFailureKind> {
let acc_addr = self.create_new_account().await;
self.operate_account_deposit_public(acc_addr, 100).await?;
self.operate_account_send_shielded_one_receiver(acc_addr, acc_addr, 100)
.await?;
Ok(())
}
///Mint utxo, privately send it to another user
pub async fn subscenario_3(&mut self) -> Result<(), ExecutionFailureKind> {
pub async fn subscenario_2(&mut self) -> Result<(), ExecutionFailureKind> {
let acc_addr = self.create_new_account().await;
let acc_addr_rec = self.create_new_account().await;
@ -1656,21 +1649,8 @@ impl NodeCore {
Ok(())
}
///Deposit balance, shielded send it to another user
pub async fn subscenario_4(&mut self) -> Result<(), ExecutionFailureKind> {
let acc_addr = self.create_new_account().await;
let acc_addr_rec = self.create_new_account().await;
self.operate_account_deposit_public(acc_addr, 100).await?;
self.operate_account_send_shielded_one_receiver(acc_addr, acc_addr_rec, 100)
.await?;
Ok(())
}
///Mint utxo, deshielded send it to another user
pub async fn subscenario_5(&mut self) -> Result<(), ExecutionFailureKind> {
pub async fn subscenario_3(&mut self) -> Result<(), ExecutionFailureKind> {
let acc_addr = self.create_new_account().await;
let acc_addr_rec = self.create_new_account().await;

View File

@ -23,8 +23,7 @@ use crate::types::{
ExecuteScenarioSplitResponse, ExecuteSubscenarioRequest, ExecuteSubscenarioResponse,
ShowAccountPublicBalanceRequest, ShowAccountPublicBalanceResponse, ShowAccountUTXORequest,
ShowAccountUTXOResponse, ShowTransactionRequest, ShowTransactionResponse,
UTXOShortEssentialStruct, WriteDepositPublicBalanceRequest,
WriteDepositPublicBalanceResponse, WriteMintPrivateUTXOMultipleAssetsRequest,
UTXOShortEssentialStruct, WriteMintPrivateUTXOMultipleAssetsRequest,
WriteMintPrivateUTXOMultipleAssetsResponse, WriteMintPrivateUTXORequest,
WriteMintPrivateUTXOResponse, WriteSendDeshieldedBalanceRequest,
WriteSendDeshieldedUTXOResponse, WriteSendPrivateUTXORequest, WriteSendPrivateUTXOResponse,
@ -42,7 +41,6 @@ pub const EXECUTE_SCENARIO_MULTIPLE_SEND: &str = "execute_scenario_multiple_send
pub const SHOW_ACCOUNT_PUBLIC_BALANCE: &str = "show_account_public_balance";
pub const SHOW_ACCOUNT_UTXO: &str = "show_account_utxo";
pub const SHOW_TRANSACTION: &str = "show_transaction";
pub const WRITE_DEPOSIT_PUBLIC_BALANCE: &str = "write_deposit_public_balance";
pub const WRITE_MINT_UTXO: &str = "write_mint_utxo";
pub const WRITE_MINT_UTXO_MULTIPLE_ASSETS: &str = "write_mint_utxo_multiple_assets";
pub const WRITE_SEND_UTXO_PRIVATE: &str = "write_send_utxo_private";
@ -92,14 +90,6 @@ impl JsonHandler {
.subscenario_3()
.await
.map_err(cast_common_execution_error_into_rpc_error)?,
4 => store
.subscenario_4()
.await
.map_err(cast_common_execution_error_into_rpc_error)?,
5 => store
.subscenario_5()
.await
.map_err(cast_common_execution_error_into_rpc_error)?,
_ => return Err(RpcErr(RpcError::invalid_params("Scenario id not found"))),
}
}
@ -312,42 +302,46 @@ impl JsonHandler {
ShowTransactionResponse {
hash: req.tx_hash,
tx_kind: tx.tx_kind,
tx_kind: tx.body().tx_kind,
public_input: if let Ok(action) =
serde_json::from_slice::<ActionData>(&tx.execution_input)
serde_json::from_slice::<ActionData>(&tx.body().execution_input)
{
action.into_hexed_print()
} else {
"".to_string()
},
public_output: if let Ok(action) =
serde_json::from_slice::<ActionData>(&tx.execution_output)
serde_json::from_slice::<ActionData>(&tx.body().execution_output)
{
action.into_hexed_print()
} else {
"".to_string()
},
utxo_commitments_created_hashes: tx
.body()
.utxo_commitments_created_hashes
.iter()
.map(|val| hex::encode(val.clone()))
.collect::<Vec<_>>(),
utxo_commitments_spent_hashes: tx
.body()
.utxo_commitments_spent_hashes
.iter()
.map(|val| hex::encode(val.clone()))
.collect::<Vec<_>>(),
utxo_nullifiers_created_hashes: tx
.body()
.nullifier_created_hashes
.iter()
.map(|val| hex::encode(val.clone()))
.collect::<Vec<_>>(),
encoded_data: tx
.body()
.encoded_data
.iter()
.map(|val| (hex::encode(val.0.clone()), hex::encode(val.1.clone())))
.collect::<Vec<_>>(),
ephemeral_pub_key: hex::encode(tx.ephemeral_pub_key.clone()),
ephemeral_pub_key: hex::encode(tx.body().ephemeral_pub_key.clone()),
}
}
};
@ -355,36 +349,6 @@ impl JsonHandler {
respond(helperstruct)
}
pub async fn process_write_deposit_public_balance(
&self,
request: Request,
) -> Result<Value, RpcErr> {
let req = WriteDepositPublicBalanceRequest::parse(Some(request.params))?;
let acc_addr_hex_dec = hex::decode(req.account_addr.clone()).map_err(|_| {
RpcError::parse_error("Failed to decode account address from hex string".to_string())
})?;
let acc_addr: [u8; 32] = acc_addr_hex_dec.try_into().map_err(|_| {
RpcError::parse_error("Failed to parse account address from bytes".to_string())
})?;
{
let mut cover_guard = self.node_chain_store.lock().await;
cover_guard
.operate_account_deposit_public(acc_addr, req.amount as u128)
.await
.map_err(cast_common_execution_error_into_rpc_error)?;
};
let helperstruct = WriteDepositPublicBalanceResponse {
status: SUCCESS.to_string(),
};
respond(helperstruct)
}
pub async fn process_write_mint_utxo(&self, request: Request) -> Result<Value, RpcErr> {
let req = WriteMintPrivateUTXORequest::parse(Some(request.params))?;
@ -777,9 +741,6 @@ impl JsonHandler {
SHOW_ACCOUNT_PUBLIC_BALANCE => self.process_show_account_public_balance(request).await,
SHOW_ACCOUNT_UTXO => self.process_show_account_utxo_request(request).await,
SHOW_TRANSACTION => self.process_show_transaction(request).await,
WRITE_DEPOSIT_PUBLIC_BALANCE => {
self.process_write_deposit_public_balance(request).await
}
WRITE_MINT_UTXO => self.process_write_mint_utxo(request).await,
WRITE_MINT_UTXO_MULTIPLE_ASSETS => {
self.process_write_mint_utxo_multiple_assets(request).await

View File

@ -1,6 +1,6 @@
use accounts::{account_core::Account, key_management::ephemeral_key_holder::EphemeralKeyHolder};
use anyhow::Result;
use common::transaction::{TransactionPayload, TxKind};
use common::transaction::{TransactionBody, TxKind};
use rand::thread_rng;
use risc0_zkvm::Receipt;
use secp256k1_zkp::{CommitmentSecrets, PedersenCommitment, Tweak};
@ -15,8 +15,8 @@ pub fn create_public_transaction_payload(
secret_r: [u8; 32],
sc_addr: String,
state_changes: (serde_json::Value, usize),
) -> TransactionPayload {
TransactionPayload {
) -> TransactionBody {
TransactionBody {
tx_kind: TxKind::Public,
execution_input,
execution_output: vec![],

View File

@ -6,22 +6,22 @@ use common::{
block::{Block, HashableBlockData},
merkle_tree_public::TreeHashType,
nullifier::UTXONullifier,
transaction::{Transaction, TxKind},
transaction::{AuthenticatedTransaction, Transaction, TransactionBody, TxKind},
utxo_commitment::UTXOCommitment,
};
use config::SequencerConfig;
use mempool::MemPool;
use mempool_transaction::MempoolTransaction;
use sequencer_store::SequecerChainStore;
use serde::{Deserialize, Serialize};
use transaction_mempool::TransactionMempool;
pub mod config;
pub mod mempool_transaction;
pub mod sequencer_store;
pub mod transaction_mempool;
pub struct SequencerCore {
pub store: SequecerChainStore,
pub mempool: MemPool<TransactionMempool>,
pub mempool: MemPool<MempoolTransaction>,
pub sequencer_config: SequencerConfig,
pub chain_height: u64,
}
@ -36,6 +36,7 @@ pub enum TransactionMalformationErrorKind {
MempoolFullForRound { tx: TreeHashType },
ChainStateFurtherThanTransactionState { tx: TreeHashType },
FailedToInsert { tx: TreeHashType, details: String },
InvalidSignature,
}
impl Display for TransactionMalformationErrorKind {
@ -55,7 +56,7 @@ impl SequencerCore {
config.is_genesis_random,
&config.initial_accounts,
),
mempool: MemPool::<TransactionMempool>::default(),
mempool: MemPool::<MempoolTransaction>::default(),
chain_height: config.genesis_id,
sequencer_config: config,
}
@ -73,31 +74,30 @@ impl SequencerCore {
pub fn transaction_pre_check(
&mut self,
tx: &Transaction,
tx: Transaction,
tx_roots: [[u8; 32]; 2],
) -> Result<(), TransactionMalformationErrorKind> {
let Transaction {
hash,
) -> Result<AuthenticatedTransaction, TransactionMalformationErrorKind> {
let tx = tx
.into_authenticated()
.map_err(|_| TransactionMalformationErrorKind::InvalidSignature)?;
let TransactionBody {
tx_kind,
ref execution_input,
ref execution_output,
ref utxo_commitments_created_hashes,
ref nullifier_created_hashes,
..
} = tx;
} = tx.transaction().body();
let mempool_size = self.mempool.len();
if mempool_size >= self.sequencer_config.max_num_tx_in_block {
return Err(TransactionMalformationErrorKind::MempoolFullForRound { tx: *hash });
}
let tx_hash = *tx.hash();
let curr_sequencer_roots = self.get_tree_roots();
if tx_roots != curr_sequencer_roots {
return Err(
TransactionMalformationErrorKind::ChainStateFurtherThanTransactionState {
tx: *hash,
tx: tx_hash,
},
);
}
@ -111,7 +111,7 @@ impl SequencerCore {
//Public transactions can not make private operations.
return Err(
TransactionMalformationErrorKind::PublicTransactionChangedPrivateData {
tx: *hash,
tx: tx_hash,
},
);
}
@ -123,7 +123,7 @@ impl SequencerCore {
//between public and private state.
return Err(
TransactionMalformationErrorKind::PrivateTransactionChangedPublicData {
tx: *hash,
tx: tx_hash,
},
);
}
@ -132,7 +132,7 @@ impl SequencerCore {
};
//Tree checks
let tx_tree_check = self.store.pub_tx_store.get_tx(*hash).is_some();
let tx_tree_check = self.store.pub_tx_store.get_tx(tx_hash).is_some();
let nullifier_tree_check = nullifier_created_hashes
.iter()
.map(|nullifier_hash| {
@ -152,52 +152,61 @@ impl SequencerCore {
.any(|check| check);
if tx_tree_check {
return Err(TransactionMalformationErrorKind::TxHashAlreadyPresentInTree { tx: *hash });
return Err(
TransactionMalformationErrorKind::TxHashAlreadyPresentInTree { tx: *tx.hash() },
);
}
if nullifier_tree_check {
return Err(
TransactionMalformationErrorKind::NullifierAlreadyPresentInTree { tx: *hash },
TransactionMalformationErrorKind::NullifierAlreadyPresentInTree { tx: *tx.hash() },
);
}
if utxo_commitments_check {
return Err(
TransactionMalformationErrorKind::UTXOCommitmentAlreadyPresentInTree { tx: *hash },
TransactionMalformationErrorKind::UTXOCommitmentAlreadyPresentInTree {
tx: *tx.hash(),
},
);
}
Ok(())
Ok(tx)
}
pub fn push_tx_into_mempool_pre_check(
&mut self,
item: TransactionMempool,
transaction: Transaction,
tx_roots: [[u8; 32]; 2],
) -> Result<(), TransactionMalformationErrorKind> {
self.transaction_pre_check(&item.tx, tx_roots)?;
let mempool_size = self.mempool.len();
if mempool_size >= self.sequencer_config.max_num_tx_in_block {
return Err(TransactionMalformationErrorKind::MempoolFullForRound {
tx: transaction.body().hash(),
});
}
self.mempool.push_item(item);
let authenticated_tx = self.transaction_pre_check(transaction, tx_roots)?;
self.mempool.push_item(authenticated_tx.into());
Ok(())
}
fn execute_check_transaction_on_state(
&mut self,
tx: TransactionMempool,
mempool_tx: &MempoolTransaction,
) -> Result<(), TransactionMalformationErrorKind> {
let Transaction {
// ToDo: remove hashing of transactions on node side [Issue #66]
hash: _,
let TransactionBody {
ref utxo_commitments_created_hashes,
ref nullifier_created_hashes,
..
} = tx.tx;
} = mempool_tx.auth_tx.transaction().body();
for utxo_comm in utxo_commitments_created_hashes {
self.store
.utxo_commitments_store
.add_tx(UTXOCommitment { hash: *utxo_comm });
.add_tx(&UTXOCommitment { hash: *utxo_comm });
}
for nullifier in nullifier_created_hashes.iter() {
@ -206,7 +215,9 @@ impl SequencerCore {
});
}
self.store.pub_tx_store.add_tx(tx.tx);
self.store
.pub_tx_store
.add_tx(mempool_tx.auth_tx.transaction());
Ok(())
}
@ -224,7 +235,7 @@ impl SequencerCore {
.pop_size(self.sequencer_config.max_num_tx_in_block);
for tx in &transactions {
self.execute_check_transaction_on_state(tx.clone())?;
self.execute_check_transaction_on_state(&tx)?;
}
let prev_block_hash = self
@ -236,7 +247,10 @@ impl SequencerCore {
let hashable_data = HashableBlockData {
block_id: new_block_height,
prev_block_id: self.chain_height,
transactions: transactions.into_iter().map(|tx_mem| tx_mem.tx).collect(),
transactions: transactions
.into_iter()
.map(|tx_mem| tx_mem.auth_tx.transaction().clone())
.collect(),
data: vec![],
prev_block_hash,
};
@ -258,10 +272,10 @@ mod tests {
use super::*;
use std::path::PathBuf;
use common::transaction::{Transaction, TxKind};
use common::transaction::{SignaturePrivateKey, Transaction, TransactionBody, TxKind};
use mempool_transaction::MempoolTransaction;
use rand::Rng;
use secp256k1_zkp::Tweak;
use transaction_mempool::TransactionMempool;
fn setup_sequencer_config_variable_initial_accounts(
initial_accounts: Vec<AccountInitialData>,
@ -301,15 +315,13 @@ mod tests {
}
fn create_dummy_transaction(
hash: TreeHashType,
nullifier_created_hashes: Vec<[u8; 32]>,
utxo_commitments_spent_hashes: Vec<[u8; 32]>,
utxo_commitments_created_hashes: Vec<[u8; 32]>,
) -> Transaction {
let mut rng = rand::thread_rng();
Transaction {
hash,
let body = TransactionBody {
tx_kind: TxKind::Private,
execution_input: vec![],
execution_output: vec![],
@ -324,13 +336,16 @@ mod tests {
secret_r: [0; 32],
sc_addr: "sc_addr".to_string(),
state_changes: (serde_json::Value::Null, 0),
}
};
Transaction::new(body, SignaturePrivateKey::random(&mut rng))
}
fn common_setup(sequencer: &mut SequencerCore) {
let tx = create_dummy_transaction([12; 32], vec![[9; 32]], vec![[7; 32]], vec![[8; 32]]);
let tx_mempool = TransactionMempool { tx };
sequencer.mempool.push_item(tx_mempool);
let tx = create_dummy_transaction(vec![[9; 32]], vec![[7; 32]], vec![[8; 32]]);
let mempool_tx = MempoolTransaction {
auth_tx: tx.into_authenticated().unwrap(),
};
sequencer.mempool.push_item(mempool_tx);
sequencer
.produce_new_block_with_mempool_transactions()
@ -454,15 +469,15 @@ mod tests {
common_setup(&mut sequencer);
let tx = create_dummy_transaction([1; 32], vec![[91; 32]], vec![[71; 32]], vec![[81; 32]]);
let tx = create_dummy_transaction(vec![[91; 32]], vec![[71; 32]], vec![[81; 32]]);
let tx_roots = sequencer.get_tree_roots();
let result = sequencer.transaction_pre_check(&tx, tx_roots);
let result = sequencer.transaction_pre_check(tx, tx_roots);
assert!(result.is_ok());
}
#[test]
fn test_transaction_pre_check_fail_mempool_full() {
fn test_push_tx_into_mempool_fails_mempool_full() {
let config = SequencerConfig {
max_num_tx_in_block: 1,
..setup_sequencer_config()
@ -471,14 +486,16 @@ mod tests {
common_setup(&mut sequencer);
let tx = create_dummy_transaction([2; 32], vec![[92; 32]], vec![[72; 32]], vec![[82; 32]]);
let tx = create_dummy_transaction(vec![[92; 32]], vec![[72; 32]], vec![[82; 32]]);
let tx_roots = sequencer.get_tree_roots();
// Fill the mempool
let dummy_tx = TransactionMempool { tx: tx.clone() };
let dummy_tx = MempoolTransaction {
auth_tx: tx.clone().into_authenticated().unwrap(),
};
sequencer.mempool.push_item(dummy_tx);
let result = sequencer.transaction_pre_check(&tx, tx_roots);
let result = sequencer.push_tx_into_mempool_pre_check(tx, tx_roots);
assert!(matches!(
result,
@ -493,11 +510,10 @@ mod tests {
common_setup(&mut sequencer);
let tx = create_dummy_transaction([3; 32], vec![[93; 32]], vec![[73; 32]], vec![[83; 32]]);
let tx = create_dummy_transaction(vec![[93; 32]], vec![[73; 32]], vec![[83; 32]]);
let tx_roots = sequencer.get_tree_roots();
let tx_mempool = TransactionMempool { tx };
let result = sequencer.push_tx_into_mempool_pre_check(tx_mempool.clone(), tx_roots);
let result = sequencer.push_tx_into_mempool_pre_check(tx, tx_roots);
assert!(result.is_ok());
assert_eq!(sequencer.mempool.len(), 1);
}
@ -507,8 +523,10 @@ mod tests {
let config = setup_sequencer_config();
let mut sequencer = SequencerCore::start_from_config(config);
let tx = create_dummy_transaction([4; 32], vec![[94; 32]], vec![[7; 32]], vec![[8; 32]]);
let tx_mempool = TransactionMempool { tx };
let tx = create_dummy_transaction(vec![[94; 32]], vec![[7; 32]], vec![[8; 32]]);
let tx_mempool = MempoolTransaction {
auth_tx: tx.into_authenticated().unwrap(),
};
sequencer.mempool.push_item(tx_mempool);
let block_id = sequencer.produce_new_block_with_mempool_transactions();

View File

@ -0,0 +1,20 @@
use common::{merkle_tree_public::TreeHashType, transaction::AuthenticatedTransaction};
use mempool::mempoolitem::MemPoolItem;
pub struct MempoolTransaction {
pub auth_tx: AuthenticatedTransaction,
}
impl From<AuthenticatedTransaction> for MempoolTransaction {
fn from(auth_tx: AuthenticatedTransaction) -> Self {
Self { auth_tx }
}
}
impl MemPoolItem for MempoolTransaction {
type Identifier = TreeHashType;
fn identifier(&self) -> Self::Identifier {
*self.auth_tx.hash()
}
}

View File

@ -1,43 +0,0 @@
use common::{merkle_tree_public::TreeHashType, transaction::Transaction};
use mempool::mempoolitem::MemPoolItem;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone)]
pub struct TransactionMempool {
pub tx: Transaction,
}
impl From<Transaction> for TransactionMempool {
fn from(value: Transaction) -> Self {
Self { tx: value }
}
}
impl Serialize for TransactionMempool {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.tx.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for TransactionMempool {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
match Transaction::deserialize(deserializer) {
Ok(tx) => Ok(TransactionMempool { tx }),
Err(err) => Err(err),
}
}
}
impl MemPoolItem for TransactionMempool {
type Identifier = TreeHashType;
fn identifier(&self) -> Self::Identifier {
self.tx.hash
}
}

View File

@ -76,10 +76,7 @@ impl JsonHandler {
{
let mut state = self.sequencer_state.lock().await;
state.push_tx_into_mempool_pre_check(
send_tx_req.transaction.into(),
send_tx_req.tx_roots,
)?;
state.push_tx_into_mempool_pre_check(send_tx_req.transaction, send_tx_req.tx_roots)?;
}
let helperstruct = SendTxResponse {

View File

@ -316,7 +316,7 @@ impl RocksDBIO {
let cf_sc = self.sc_column();
let sc_addr_loc = format!("{sc_addr:?}{SC_LEN_SUFFIX}");
let sc_len_addr = sc_addr_loc.as_str().as_bytes();
let sc_len_addr = sc_addr_loc.as_bytes();
self.db
.put_cf(&cf_sc, sc_len_addr, length.to_be_bytes())
@ -360,7 +360,7 @@ impl RocksDBIO {
let cf_sc = self.sc_column();
let sc_addr_loc = format!("{sc_addr:?}{SC_LEN_SUFFIX}");
let sc_len_addr = sc_addr_loc.as_str().as_bytes();
let sc_len_addr = sc_addr_loc.as_bytes();
let sc_len = self
.db
@ -379,11 +379,11 @@ impl RocksDBIO {
///Get full sc state from DB
pub fn get_sc_sc_state(&self, sc_addr: &str) -> DbResult<Vec<DataBlob>> {
let cf_sc = self.sc_column();
let sc_len = self.get_sc_sc_state_len(&sc_addr)?;
let sc_len = self.get_sc_sc_state_len(sc_addr)?;
let mut data_blob_list = vec![];
for id in 0..sc_len {
let blob_addr = produce_address_for_data_blob_at_id(&sc_addr, id);
let blob_addr = produce_address_for_data_blob_at_id(sc_addr, id);
let blob = self
.db
@ -541,7 +541,7 @@ impl RocksDBIO {
///Creates address for sc data blob at corresponding id
fn produce_address_for_data_blob_at_id(sc_addr: &str, id: usize) -> Vec<u8> {
let mut prefix_bytes: Vec<u8> = sc_addr.as_bytes().iter().cloned().collect();
let mut prefix_bytes: Vec<u8> = sc_addr.as_bytes().to_vec();
let id_bytes = id.to_be_bytes();

View File

@ -58,7 +58,7 @@ impl UTXO {
}
pub fn create_utxo_from_payload(payload_with_asset: UTXOPayload) -> Self {
let mut hasher = sha2::Sha256::new();
hasher.update(&payload_with_asset.to_bytes());
hasher.update(payload_with_asset.to_bytes());
let hash = <TreeHashType>::from(hasher.finalize_fixed());
Self {