Skip to content

Commit a0157a6

Browse files
committed
Cleanup
1 parent cf3d4fa commit a0157a6

File tree

8 files changed

+78
-123
lines changed

8 files changed

+78
-123
lines changed

bin/stf-runner-demo/README.md

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -34,14 +34,7 @@ The STF Runner Demo provides a hands-on way to understand how the Orchestration
3434
From the project root:
3535

3636
```bash
37-
cargo run --bin stf-runner-demo
38-
```
39-
40-
Or from the demo directory:
41-
42-
```bash
43-
cd bin/stf-runner-demo
44-
cargo run
37+
cargo run -p stf-runner-demo
4538
```
4639

4740
## Usage

bin/stf-runner-demo/main.rs

Lines changed: 5 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ impl StateAccessor<OLState> for SimpleStateAccessor {
112112

113113
fn create_minimal_params() -> RollupParams {
114114
RollupParams {
115-
magic_bytes: "demo".as_bytes().try_into().unwrap_or([0u8; 4]).into(),
115+
magic_bytes: "demo".as_bytes().try_into().unwrap_or([0u8; 4]),
116116
block_time: 1000,
117117
da_tag: "demo-da".to_string(),
118118
checkpoint_tag: "demo-ckpt".to_string(),
@@ -353,18 +353,18 @@ fn main() -> anyhow::Result<()> {
353353
println!(" Bridge Account: {} for withdrawals", bridge_hex);
354354

355355
// Update state accessor with the correct accounts root after creating accounts
356-
let accounts_root = ledger.root().expect("Failed to compute accounts root");
356+
let accounts_root = ledger
357+
.accounts_root()
358+
.expect("Failed to compute accounts root");
357359
state_accessor.set_accounts_root(accounts_root);
358360

359361
// Process genesis block automatically on startup
360362
println!("\nProcessing genesis block...");
361363
let genesis_block = create_genesis_block();
362364
let genesis_prev_header =
363365
OLBlockHeader::new(0, 0, 0, Buf32::zero(), Buf32::zero(), Buf32::zero());
364-
let state_clone = state_accessor.get_toplevel_state().clone();
365366

366367
match process_block(
367-
&state_clone,
368368
&genesis_prev_header,
369369
&genesis_block,
370370
&params,
@@ -432,9 +432,7 @@ fn main() -> anyhow::Result<()> {
432432

433433
// Create a clone of the state for the first parameter (it's unused
434434
// according to comments)
435-
let state_clone = state_accessor.get_toplevel_state().clone();
436435
match process_block(
437-
&state_clone,
438436
&last_header,
439437
&block,
440438
&params,
@@ -479,9 +477,7 @@ fn main() -> anyhow::Result<()> {
479477

480478
// Create a clone of the state for the first parameter (it's unused
481479
// according to comments)
482-
let state_clone = state_accessor.get_toplevel_state().clone();
483480
match process_block(
484-
&state_clone,
485481
&last_header,
486482
&block,
487483
&params,
@@ -519,9 +515,7 @@ fn main() -> anyhow::Result<()> {
519515

520516
// Create a clone of the state for the first parameter (it's unused according to
521517
// comments)
522-
let state_clone = state_accessor.get_toplevel_state().clone();
523518
match process_block(
524-
&state_clone,
525519
&last_header,
526520
&block,
527521
&params,
@@ -549,9 +543,7 @@ fn main() -> anyhow::Result<()> {
549543

550544
// Create a clone of the state for the first parameter (it's unused according to
551545
// comments)
552-
let state_clone = state_accessor.get_toplevel_state().clone();
553546
match process_block(
554-
&state_clone,
555547
&last_header,
556548
&block,
557549
&params,
@@ -613,7 +605,7 @@ fn show_accounts(ledger: &InMemoryVectorLedger) {
613605
for i in 0..2 {
614606
let account_id = Buf32::from([i as u8; 32]);
615607
let account_hex = hex::encode(account_id.as_bytes());
616-
match ledger.account_state(&account_id) {
608+
match ledger.get_account_state(&account_id) {
617609
Ok(Some(account)) => {
618610
println!(
619611
" Account {}: {} balance = {} sats",

crates/chain-worker/src/state.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,4 +80,12 @@ impl StateAccessor for WbStateAccessorImpl {
8080
fn set_epoch_finishing_flag(&mut self, flag: bool) {
8181
self.toplevel_chs_cache.set_epoch_finishing_flag(flag);
8282
}
83+
84+
fn get_toplevel_state(&mut self) -> &Chainstate {
85+
self.toplevel_chs_cache.state()
86+
}
87+
88+
fn set_accounts_root(&mut self, _root: Buf32) {
89+
todo!()
90+
}
8391
}

crates/services/stf-runner/src/block.rs

Lines changed: 14 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,6 @@ pub struct AsmManifest {
9595
#[derive(Debug, Clone)]
9696
pub struct OLLog {
9797
account_serial: u32,
98-
account_id: AccountId,
9998
payload: Vec<u8>, // TODO: make this typed, serialization can be done at the edges
10099
}
101100

@@ -122,17 +121,19 @@ impl OLBlock {
122121
) -> Result<(), String> {
123122
let current_header = self.signed_header.header();
124123

125-
if current_header.slot() > 0 && current_header.slot() != prev_header.slot() + 1 {
126-
return Err(format!("Invalid block slot {}", current_header.slot()));
127-
}
128-
if current_header.slot() > 0
129-
&& *current_header.parent_blockid() != prev_header.compute_header_root()
130-
{
131-
return Err("Invalid parent block ID".to_string());
124+
if current_header.slot() > 0 {
125+
if current_header.slot() != prev_header.slot() + 1 {
126+
return Err(format!("Invalid block slot {}", current_header.slot()));
127+
}
128+
if *current_header.parent_blockid() != prev_header.compute_header_root() {
129+
return Err("Invalid parent block ID".to_string());
130+
}
132131
}
133132

134-
// Check epoch progression - epoch should not decrease
135-
if current_header.epoch() != 0 && current_header.epoch() < prev_header.epoch() {
133+
// Check epoch progression - epoch should not decrease and increase only by 1 at max
134+
let same_epoch = current_header.epoch() == prev_header.epoch();
135+
let valid_increment = current_header.epoch() == prev_header.epoch() + 1;
136+
if current_header.epoch() != 0 && (same_epoch || valid_increment) {
136137
return Err(format!(
137138
"Epoch regression: current {} < previous {}",
138139
current_header.epoch, prev_header.epoch
@@ -276,7 +277,8 @@ impl Transaction {
276277
&self.extra
277278
}
278279

279-
/// The account id this transaction belongs to. Maybe we should also store sequencer pubkey
280+
/// The account id this transaction is on behalf of. `target` is confusing.
281+
/// Maybe we could also store sequencer pubkey
280282
/// along with vk? and then we can have transactions to update the pubkey if sequencer needs to
281283
/// rotate. Just a thought.
282284
pub fn account_id(&self) -> AccountId {
@@ -339,10 +341,9 @@ impl AsmManifest {
339341
}
340342

341343
impl OLLog {
342-
pub fn new(account_serial: u32, account_id: AccountId, payload: Vec<u8>) -> Self {
344+
pub fn new(account_serial: u32, payload: Vec<u8>) -> Self {
343345
Self {
344346
account_serial,
345-
account_id,
346347
payload,
347348
}
348349
}
@@ -351,10 +352,6 @@ impl OLLog {
351352
self.account_serial
352353
}
353354

354-
pub fn account_id(&self) -> &AccountId {
355-
&self.account_id
356-
}
357-
358355
pub fn payload(&self) -> &[u8] {
359356
&self.payload
360357
}

crates/services/stf-runner/src/ledger.rs

Lines changed: 28 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@ use sha2::{Digest, Sha256};
44
use strata_primitives::buf::Buf32;
55
use thiserror::Error;
66

7-
use crate::account::{AccountId, AccountSerial, AccountState, SnarkAccountMessageEntry};
7+
use crate::account::{
8+
AccountId, AccountInnerState, AccountSerial, AccountState, SnarkAccountMessageEntry,
9+
};
810

911
#[derive(Debug, Error)]
1012
pub enum LedgerError {}
@@ -14,18 +16,21 @@ pub type LedgerResult<T> = Result<T, LedgerError>;
1416
/// Interface for accessing and modifying accounts ledger
1517
pub trait LedgerProvider {
1618
/// Root of the current accounts ledger. For example root of the accounts trie.
17-
fn root(&self) -> LedgerResult<Buf32>;
19+
fn accounts_root(&self) -> LedgerResult<Buf32>;
1820

1921
/// Get account id from serial
20-
fn account_id(&self, serial: AccountSerial) -> LedgerResult<Option<AccountId>>;
22+
fn get_account_id(&self, serial: AccountSerial) -> LedgerResult<Option<AccountId>>;
2123

2224
/// Get an account state
23-
fn account_state(&self, acct_id: &AccountId) -> LedgerResult<Option<AccountState>>;
25+
fn get_account_state(&self, acct_id: &AccountId) -> LedgerResult<Option<AccountState>>;
2426

2527
/// Convenient method for accessing state via serial.
26-
fn account_serial_state(&self, serial: AccountSerial) -> LedgerResult<Option<AccountState>> {
27-
if let Some(acct_id) = self.account_id(serial)? {
28-
self.account_state(&acct_id)
28+
fn get_account_state_by_serial(
29+
&self,
30+
serial: AccountSerial,
31+
) -> LedgerResult<Option<AccountState>> {
32+
if let Some(acct_id) = self.get_account_id(serial)? {
33+
self.get_account_state(&acct_id)
2934
} else {
3035
Ok(None)
3136
}
@@ -42,23 +47,14 @@ pub trait LedgerProvider {
4247
// TODO: message can be a bit generic instead of snark message?
4348
fn insert_message(
4449
&mut self,
45-
acct_id: AccountId,
50+
acct_id: &AccountId,
4651
message: SnarkAccountMessageEntry,
4752
) -> LedgerResult<()>;
48-
49-
/// Consume input messages. Most likely updates some input index in state
50-
fn consume_messages(
51-
&mut self,
52-
acct_id: AccountId,
53-
from_idx: u64,
54-
to_idx: u64,
55-
) -> LedgerResult<()>;
5653
}
5754

5855
/// Simplest in-memory ledger. All it has is an in-memory map of acct id to list of messages.
5956
#[derive(Debug, Clone)]
6057
pub struct InMemoryVectorLedger {
61-
pub acct_msgs: HashMap<AccountId, Vec<SnarkAccountMessageEntry>>,
6258
pub serial_to_id: HashMap<AccountSerial, AccountId>,
6359
pub account_states: HashMap<AccountId, AccountState>,
6460
pub root_cache: Option<Buf32>,
@@ -67,7 +63,6 @@ pub struct InMemoryVectorLedger {
6763
impl InMemoryVectorLedger {
6864
pub fn new() -> Self {
6965
Self {
70-
acct_msgs: HashMap::new(),
7166
serial_to_id: HashMap::new(),
7267
account_states: HashMap::new(),
7368
root_cache: None,
@@ -77,7 +72,6 @@ impl InMemoryVectorLedger {
7772
pub fn create_account(&mut self, serial: AccountSerial, id: AccountId, state: AccountState) {
7873
self.serial_to_id.insert(serial, id);
7974
self.account_states.insert(id, state);
80-
self.acct_msgs.insert(id, Vec::new());
8175
self.invalidate_root_cache();
8276
}
8377

@@ -90,7 +84,6 @@ impl InMemoryVectorLedger {
9084
return Ok(*cached);
9185
}
9286

93-
use sha2::{Digest, Sha256};
9487
let mut hasher = Sha256::new();
9588

9689
// Sort account IDs for deterministic ordering
@@ -100,9 +93,9 @@ impl InMemoryVectorLedger {
10093
for account_id in sorted_accounts {
10194
hasher.update(account_id.as_ref());
10295
if let Some(state) = self.account_states.get(account_id) {
103-
hasher.update(&state.serial.to_be_bytes());
104-
hasher.update(&state.ty.to_be_bytes());
105-
hasher.update(&state.balance.to_be_bytes());
96+
hasher.update(state.serial.to_be_bytes());
97+
hasher.update(state.ty.to_be_bytes());
98+
hasher.update(state.balance.to_be_bytes());
10699
}
107100
}
108101

@@ -119,7 +112,7 @@ impl Default for InMemoryVectorLedger {
119112
}
120113

121114
impl LedgerProvider for InMemoryVectorLedger {
122-
fn root(&self) -> LedgerResult<Buf32> {
115+
fn accounts_root(&self) -> LedgerResult<Buf32> {
123116
// Need mutable access to compute/cache root, but trait requires &self
124117
// For now, recompute every time (inefficient but correct)
125118
let mut hasher = Sha256::new();
@@ -130,53 +123,33 @@ impl LedgerProvider for InMemoryVectorLedger {
130123
for account_id in sorted_accounts {
131124
hasher.update(account_id.as_ref());
132125
if let Some(state) = self.account_states.get(account_id) {
133-
hasher.update(&state.serial.to_be_bytes());
134-
hasher.update(&state.ty.to_be_bytes());
135-
hasher.update(&state.balance.to_be_bytes());
126+
hasher.update(state.serial.to_be_bytes());
127+
hasher.update(state.ty.to_be_bytes());
128+
hasher.update(state.balance.to_be_bytes());
136129
}
137130
}
138131

139132
Ok(Buf32::new(hasher.finalize().into()))
140133
}
141134

142-
fn account_id(&self, serial: AccountSerial) -> LedgerResult<Option<AccountId>> {
135+
fn get_account_id(&self, serial: AccountSerial) -> LedgerResult<Option<AccountId>> {
143136
Ok(self.serial_to_id.get(&serial).copied())
144137
}
145138

146-
fn account_state(&self, acct_id: &AccountId) -> LedgerResult<Option<AccountState>> {
139+
fn get_account_state(&self, acct_id: &AccountId) -> LedgerResult<Option<AccountState>> {
147140
Ok(self.account_states.get(acct_id).cloned())
148141
}
149142

150143
fn insert_message(
151144
&mut self,
152-
acct_id: AccountId,
145+
acct_id: &AccountId,
153146
message: SnarkAccountMessageEntry,
154147
) -> LedgerResult<()> {
155-
self.acct_msgs
156-
.entry(acct_id)
157-
.or_insert_with(Vec::new)
158-
.push(message);
159-
self.invalidate_root_cache();
160-
Ok(())
161-
}
162-
163-
fn consume_messages(
164-
&mut self,
165-
acct_id: AccountId,
166-
from_idx: u64,
167-
to_idx: u64,
168-
) -> LedgerResult<()> {
169-
if let Some(messages) = self.acct_msgs.get_mut(&acct_id) {
170-
let from_idx = from_idx as usize;
171-
let to_idx = to_idx as usize;
172-
173-
// Validate indices
174-
if from_idx > to_idx || to_idx > messages.len() {
175-
return Ok(()); // Invalid range, do nothing
176-
}
177-
178-
// Remove consumed messages by draining the range
179-
messages.drain(from_idx..to_idx);
148+
if let Some(AccountInnerState::Snark(mut acct)) =
149+
self.get_account_state(acct_id)?.map(|a| a.inner_state)
150+
{
151+
// TODO: Will this actually update the hashmap?
152+
acct.input.push(message);
180153
self.invalidate_root_cache();
181154
}
182155
Ok(())

crates/services/stf-runner/src/state.rs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ pub struct OLState {
99
cur_epoch: u64,
1010
}
1111

12-
/// Represents the view of Layer 1 blockchain from the perspective of the OL
12+
/// Represents the view of the layer 1 blockchain from the perspective of the OL
1313
#[derive(Debug, Clone, Default)]
1414
pub struct L1View {
1515
block_hash: Buf32,
@@ -58,6 +58,7 @@ impl OLState {
5858
self.cur_epoch = cur_epoch;
5959
}
6060

61+
// NOTE: will be redundant with SSZ
6162
pub fn compute_root(&self) -> Buf32 {
6263
use sha2::{Digest, Sha256};
6364
let mut hasher = Sha256::new();
@@ -67,11 +68,11 @@ impl OLState {
6768

6869
// Hash L1 view components
6970
hasher.update(self.l1_view.block_hash.as_ref());
70-
hasher.update(&self.l1_view.block_height.to_be_bytes());
71+
hasher.update(self.l1_view.block_height.to_be_bytes());
7172

7273
// Hash current slot and epoch
73-
hasher.update(&self.cur_slot.to_be_bytes());
74-
hasher.update(&self.cur_epoch.to_be_bytes());
74+
hasher.update(self.cur_slot.to_be_bytes());
75+
hasher.update(self.cur_epoch.to_be_bytes());
7576

7677
Buf32::new(hasher.finalize().into())
7778
}

0 commit comments

Comments
 (0)