Skip to content
This repository has been archived by the owner on Jun 3, 2020. It is now read-only.

Use an initial height of 0 in default chain state (fixes #369) #373

Merged
merged 1 commit into from
Dec 12, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 30 additions & 17 deletions src/chain/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,35 +28,30 @@ pub struct State {

impl State {
/// Load the state from the given path
pub fn load_state<P>(path: P) -> Result<State, Error>
pub fn load_state<P>(path: P) -> Result<Self, Error>
where
P: AsRef<Path>,
{
let mut lst = State {
consensus_state: consensus::State::default(),
state_file_path: path.as_ref().to_owned(),
};

match fs::read_to_string(path.as_ref()) {
Ok(contents) => {
lst.consensus_state = serde_json::from_str(&contents).map_err(|e| {
Ok(state_json) => {
let consensus_state = serde_json::from_str(&state_json).map_err(|e| {
err!(
ParseError,
"error parsing {}: {}",
path.as_ref().display(),
e
)
})?;
Ok(lst)

Ok(Self {
consensus_state,
state_file_path: path.as_ref().to_owned(),
})
}
Err(e) => {
if e.kind() == io::ErrorKind::NotFound {
lst.sync_to_disk()?;
Ok(lst)
} else {
Err(e.into())
}
Err(e) if e.kind() == io::ErrorKind::NotFound => {
Self::write_initial_state(path.as_ref())
}
Err(e) => Err(Error::from(e)),
}
}

Expand Down Expand Up @@ -163,8 +158,26 @@ impl State {
Ok(())
}

/// Write the initial state to the given path on disk
fn write_initial_state(path: &Path) -> Result<Self, Error> {
let mut consensus_state = consensus::State::default();

// TODO(tarcieri): correct upstream `tendermint-rs` default height to 0
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would be good to change this upstream in tendermint-rs, then we can just rely on consensus::State::default()

// Set the initial block height to 0 to indicate we've never signed a block
consensus_state.height = 0.into();

let initial_state = Self {
consensus_state,
state_file_path: path.to_owned(),
};

initial_state.sync_to_disk()?;

Ok(initial_state)
}

/// Sync the current state to disk
fn sync_to_disk(&mut self) -> std::io::Result<()> {
fn sync_to_disk(&self) -> io::Result<()> {
let json = serde_json::to_string(&self.consensus_state)?;

AtomicFile::new(&self.state_file_path, OverwriteBehavior::AllowOverwrite)
Expand Down