Skip to content

Commit

Permalink
[sequencer] Add sequencer timestamp to TransactinoInfo and update tim…
Browse files Browse the repository at this point in the history
…estamp (#1726)

* [sequencer] Add sequencer timestamp to TransactinoInfo and update timestamp

* add integration test for timestamp
  • Loading branch information
jolestar authored May 23, 2024
1 parent 0ce680a commit 58f0bb6
Show file tree
Hide file tree
Showing 22 changed files with 285 additions and 101 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,6 @@ CREATE TABLE transactions (
gas_used BIGINT NOT NULL,
status VARCHAR NOT NULL,

tx_order_auth_validator_id BIGINT NOT NULL,
tx_order_authenticator_payload BLOB NOT NULL,

created_at BIGINT NOT NULL,
UNIQUE (tx_hash)
);
Expand Down
10 changes: 0 additions & 10 deletions crates/rooch-indexer/src/models/transactions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,6 @@ pub struct StoredTransaction {
#[diesel(sql_type = diesel::sql_types::Text)]
pub status: String,

/// The tx order signature,
#[diesel(sql_type = diesel::sql_types::BigInt)]
pub tx_order_auth_validator_id: i64,
#[diesel(sql_type = diesel::sql_types::Blob)]
pub tx_order_authenticator_payload: Vec<u8>,

#[diesel(sql_type = diesel::sql_types::BigInt)]
pub created_at: i64,
}
Expand All @@ -83,10 +77,6 @@ impl From<IndexedTransaction> for StoredTransaction {
event_root: format!("{:?}", transaction.event_root),
gas_used: transaction.gas_used as i64,
status: transaction.status,

tx_order_auth_validator_id: transaction.tx_order_auth_validator_id as i64,
tx_order_authenticator_payload: transaction.tx_order_authenticator_payload,

created_at: transaction.created_at as i64,
}
}
Expand Down
2 changes: 0 additions & 2 deletions crates/rooch-indexer/src/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,6 @@ diesel::table! {
event_root -> Text,
gas_used -> BigInt,
status -> Text,
tx_order_auth_validator_id -> BigInt,
tx_order_authenticator_payload -> Binary,
created_at -> BigInt,
}
}
Expand Down
16 changes: 2 additions & 14 deletions crates/rooch-indexer/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,6 @@ pub struct IndexedTransaction {
pub gas_used: u64,
// the vm status.
pub status: String,
// The tx order signature,
pub tx_order_auth_validator_id: u64,
pub tx_order_authenticator_payload: Vec<u8>,

pub created_at: u64,
}
Expand Down Expand Up @@ -92,15 +89,7 @@ impl IndexedTransaction {
// the vm status.
status,

// The tx order signature,
tx_order_auth_validator_id: transaction
.sequence_info
.tx_order_signature
.auth_validator_id,
tx_order_authenticator_payload: transaction.sequence_info.tx_order_signature.payload,

//TODO record transaction timestamp
created_at: 0,
created_at: transaction.sequence_info.tx_timestamp,
};
Ok(indexed_transaction)
}
Expand Down Expand Up @@ -146,8 +135,7 @@ impl IndexedEvent {
tx_order: transaction.sequence_info.tx_order,
sender: moveos_tx.ctx.sender,

//TODO record transaction timestamp
created_at: 0,
created_at: transaction.sequence_info.tx_timestamp,
}
}
}
Expand Down
23 changes: 6 additions & 17 deletions crates/rooch-open-rpc-spec/schemas/openrpc.json
Original file line number Diff line number Diff line change
Expand Up @@ -675,21 +675,6 @@
}
]
},
"AuthenticatorView": {
"type": "object",
"required": [
"auth_validator_id",
"payload"
],
"properties": {
"auth_validator_id": {
"$ref": "#/components/schemas/u64"
},
"payload": {
"$ref": "#/components/schemas/alloc::vec::Vec<u8>"
}
}
},
"BalanceInfoView": {
"type": "object",
"required": [
Expand Down Expand Up @@ -2556,7 +2541,8 @@
"required": [
"tx_accumulator_root",
"tx_order",
"tx_order_signature"
"tx_order_signature",
"tx_timestamp"
],
"properties": {
"tx_accumulator_root": {
Expand All @@ -2566,7 +2552,10 @@
"$ref": "#/components/schemas/u64"
},
"tx_order_signature": {
"$ref": "#/components/schemas/AuthenticatorView"
"$ref": "#/components/schemas/alloc::vec::Vec<u8>"
},
"tx_timestamp": {
"$ref": "#/components/schemas/u64"
}
}
},
Expand Down
4 changes: 3 additions & 1 deletion crates/rooch-pipeline-processor/src/actor/processor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,10 @@ impl PipelineProcessorActor {
pub async fn execute_tx(
&mut self,
tx: LedgerTransaction,
moveos_tx: VerifiedMoveOSTransaction,
mut moveos_tx: VerifiedMoveOSTransaction,
) -> Result<ExecuteTransactionResponse> {
// Add sequence info to tx context, let the Move contract can get the sequence info
moveos_tx.ctx.add(tx.sequence_info.clone())?;
// Then execute
let (output, execution_info) = self.executor.execute_transaction(moveos_tx.clone()).await?;
self.proposer
Expand Down
8 changes: 4 additions & 4 deletions crates/rooch-rpc-api/src/jsonrpc_types/execute_tx_response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,18 +98,18 @@ impl From<Authenticator> for AuthenticatorView {
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct TransactionSequenceInfoView {
pub tx_order: StrView<u64>,
pub tx_order_signature: AuthenticatorView,
pub tx_order_signature: BytesView,
pub tx_accumulator_root: H256View,
pub tx_timestamp: StrView<u64>,
}

impl From<TransactionSequenceInfo> for TransactionSequenceInfoView {
fn from(transaction_sequence_info: TransactionSequenceInfo) -> Self {
Self {
tx_order: StrView(transaction_sequence_info.tx_order),
tx_order_signature: AuthenticatorView::from(
transaction_sequence_info.tx_order_signature,
),
tx_order_signature: transaction_sequence_info.tx_order_signature.into(),
tx_accumulator_root: transaction_sequence_info.tx_accumulator_root.into(),
tx_timestamp: StrView(transaction_sequence_info.tx_timestamp),
}
}
}
Expand Down
9 changes: 8 additions & 1 deletion crates/rooch-sequencer/src/actor/sequencer.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// Copyright (c) RoochNetwork
// SPDX-License-Identifier: Apache-2.0

use std::time::SystemTime;

use crate::messages::{
GetSequencerOrderMessage, GetTransactionByHashMessage, GetTransactionsByHashMessage,
GetTxHashsMessage, TransactionSequenceMessage,
Expand Down Expand Up @@ -40,6 +42,8 @@ impl SequencerActor {
}

pub fn sequence(&mut self, mut tx_data: LedgerTxData) -> Result<LedgerTransaction> {
let now = SystemTime::now();
let tx_timestamp = now.duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as u64;
let tx_order = if self.last_order == 1 {
let last_order_opt = self
.rooch_store
Expand All @@ -57,13 +61,16 @@ impl SequencerActor {
let mut witness_data = hash.as_ref().to_vec();
witness_data.extend(tx_order.to_le_bytes().iter());
let witness_hash = h256::sha3_256_of(&witness_data);
let tx_order_signature = Signature::new_hashed(&witness_hash.0, &self.sequencer_key).into();
let tx_order_signature = Signature::new_hashed(&witness_hash.0, &self.sequencer_key)
.as_ref()
.to_vec();

let tx_accumulator_root = H256::random();
let tx_sequence_info = TransactionSequenceInfo {
tx_order,
tx_order_signature,
tx_accumulator_root,
tx_timestamp,
};

let tx = LedgerTransaction::new(tx_data, tx_sequence_info);
Expand Down
61 changes: 40 additions & 21 deletions crates/rooch-types/src/crypto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ use crate::{
address::RoochAddress,
authentication_key::AuthenticationKey,
error::{RoochError, RoochResult},
framework::auth_validator::BuiltinAuthValidator,
};
use derive_more::{AsMut, AsRef, From};
pub use enum_dispatch::enum_dispatch;
Expand Down Expand Up @@ -34,6 +33,25 @@ use std::{hash::Hash, str::FromStr};

pub type DefaultHash = Blake2b256;

pub enum SignatureScheme {
Ed25519,
}

impl SignatureScheme {
pub fn flag(&self) -> u8 {
match self {
SignatureScheme::Ed25519 => 0,
}
}

pub fn from_flag_byte(byte_int: u8) -> Result<SignatureScheme, RoochError> {
match byte_int {
0 => Ok(SignatureScheme::Ed25519),
_ => Err(RoochError::InvalidSignatureScheme),
}
}
}

#[allow(clippy::large_enum_variant)]
#[derive(Debug, From, PartialEq, Eq)]
pub enum RoochKeyPair {
Expand All @@ -56,6 +74,13 @@ impl RoochKeyPair {
RoochKeyPair::Ed25519(kp) => RoochKeyPair::Ed25519(kp.copy()),
}
}

#[cfg(test)]
pub fn generate_for_testing() -> Self {
let rng = &mut rand::thread_rng();
let ed25519_keypair = Ed25519KeyPair::generate(rng);
RoochKeyPair::Ed25519(ed25519_keypair)
}
}

impl Signer<Signature> for RoochKeyPair {
Expand Down Expand Up @@ -92,13 +117,15 @@ impl EncodeDecodeBase64 for RoochKeyPair {
/// Decode a RoochKeyPair from `flag || privkey` in Base64. The public key is computed directly from the private key bytes.
fn decode_base64(value: &str) -> Result<Self, eyre::Report> {
let bytes = Base64::decode(value).map_err(|e| eyre!("{}", e.to_string()))?;
match BuiltinAuthValidator::from_flag_byte(
match SignatureScheme::from_flag_byte(
*bytes.first().ok_or_else(|| eyre!("Invalid length"))?,
) {
// Process Rooch key pair by default
Ok(_x) => Ok(RoochKeyPair::Ed25519(Ed25519KeyPair::from_bytes(
bytes.get(1..).ok_or_else(|| eyre!("Invalid length"))?,
)?)),
Ok(scheme) => match scheme {
SignatureScheme::Ed25519 => Ok(RoochKeyPair::Ed25519(Ed25519KeyPair::from_bytes(
bytes.get(1..).ok_or_else(|| eyre!("Invalid length"))?,
)?)),
},
_ => Err(eyre!("Invalid bytes")),
}
}
Expand Down Expand Up @@ -151,7 +178,7 @@ impl EncodeDecodeBase64 for PublicKey {
let bytes = Base64::decode(value).map_err(|e| eyre!("{}", e.to_string()))?;
match bytes.first() {
Some(x) => {
if x == &BuiltinAuthValidator::Rooch.flag() {
if x == &SignatureScheme::Ed25519.flag() {
let pk: Ed25519PublicKey = Ed25519PublicKey::from_bytes(
bytes.get(1..).ok_or_else(|| eyre!("Invalid length"))?,
)?;
Expand Down Expand Up @@ -193,16 +220,8 @@ impl PublicKey {
PublicKey::Ed25519(_) => Ed25519RoochSignature::SCHEME.flag(),
}
}
pub fn try_from_bytes(
_auth_validator: BuiltinAuthValidator,
key_bytes: &[u8],
) -> Result<PublicKey, eyre::Report> {
// Process Rooch public key by default
Ok(PublicKey::Ed25519(
(&Ed25519PublicKey::from_bytes(key_bytes)?).into(),
))
}
pub fn auth_validator(&self) -> BuiltinAuthValidator {

pub fn auth_validator(&self) -> SignatureScheme {
match self {
PublicKey::Ed25519(_) => Ed25519RoochSignature::SCHEME,
}
Expand All @@ -218,11 +237,11 @@ impl PublicKey {
}

pub trait RoochPublicKey: VerifyingKey {
const SIGNATURE_SCHEME: BuiltinAuthValidator;
const SIGNATURE_SCHEME: SignatureScheme;
}

impl RoochPublicKey for Ed25519PublicKey {
const SIGNATURE_SCHEME: BuiltinAuthValidator = BuiltinAuthValidator::Rooch;
const SIGNATURE_SCHEME: SignatureScheme = SignatureScheme::Ed25519;
}

impl<T: RoochPublicKey> From<&T> for RoochAddress {
Expand Down Expand Up @@ -269,7 +288,7 @@ pub trait RoochSignatureInner: Sized + ToFromBytes + PartialEq + Eq + Hash {
type KeyPair: KeypairTraits<PubKey = Self::PubKey, Sig = Self::Sig>;

const LENGTH: usize = Self::Sig::LENGTH + Self::PubKey::LENGTH + 1;
const SCHEME: BuiltinAuthValidator = Self::PubKey::SIGNATURE_SCHEME;
const SCHEME: SignatureScheme = Self::PubKey::SIGNATURE_SCHEME;

fn get_verification_inputs(
&self,
Expand Down Expand Up @@ -442,7 +461,7 @@ impl AsRef<[u8]> for CompressedSignature {
pub trait RoochSignature: Sized + ToFromBytes {
fn signature_bytes(&self) -> &[u8];
fn public_key_bytes(&self) -> &[u8];
fn auth_validator(&self) -> BuiltinAuthValidator;
fn scheme(&self) -> SignatureScheme;

fn verify_secure<T>(&self, value: &T, author: RoochAddress) -> RoochResult<()>
where
Expand All @@ -462,7 +481,7 @@ impl<S: RoochSignatureInner + Sized> RoochSignature for S {
&self.as_ref()[S::Sig::LENGTH + 1..]
}

fn auth_validator(&self) -> BuiltinAuthValidator {
fn scheme(&self) -> SignatureScheme {
S::PubKey::SIGNATURE_SCHEME
}

Expand Down
2 changes: 2 additions & 0 deletions crates/rooch-types/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,8 @@ pub enum RoochError {
InvalidChainID,
#[error("Invalid password error: {0}")]
InvalidPasswordError(String),
#[error("Invalid signature scheme error")]
InvalidSignatureScheme,

#[error("Clean server error: {0}")]
CleanServerError(String),
Expand Down
4 changes: 2 additions & 2 deletions crates/rooch-types/src/test_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ pub fn random_rooch_transaction() -> RoochTransaction {
pub fn random_ledger_transaction() -> LedgerTransaction {
let rooch_transaction = random_rooch_transaction();

let tx_order_signature = Authenticator::new(rand::random(), random_bytes());
let tx_order_signature = random_bytes();
let random_sequence_info =
TransactionSequenceInfo::new(rand::random(), tx_order_signature, H256::random());
TransactionSequenceInfo::new(rand::random(), tx_order_signature, H256::random(), 0);
LedgerTransaction::new_l2_tx(rooch_transaction, random_sequence_info)
}

Expand Down
Loading

0 comments on commit 58f0bb6

Please sign in to comment.