Photo by micheile henderson on Unsplash

Member-only story

Building a Blockchain from Scratch in Rust (part 2)

Byte Blog

--

This article is open to everyone, non-members can access it via this link

In part 1 we created the bare bones of a blockchain implementation, in this part we shall supercharge it by adding persistence and transactions.

Full updated code is available at the end of the tutorial.

Adding Persistence

Let’s face it: nobody wants to lose their hard-earned blockchain data. With persistence, you can save your blockchain to a file and load it back whenever you want.

In the blockchain.rs file, we introduce two functions:

  1. save_to_file(&self, filename: &str): Saves the blockchain as JSON to a file.
  2. load_from_file(filename: &str) -> Self: Loads the blockchain from a JSON file.
    pub fn save_to_file(&self, filename: &str) {
let data = serde_json::to_string(self).unwrap();
fs::write(filename, data).expect("Unable to save blockchain to file");
}

pub fn load_from_file(filename: &str) -> Self {
let data = fs::read_to_string(filename).expect("Unable to load blockchain from file");
serde_json::from_str(&data).unwrap()
}

Implementing Transactions

--

--

No responses yet