owned this note
owned this note
Published
Linked with GitHub
# Creating Your First Substrate Blockchain
In this tutorial, you will learn to create a custom ["Proof Of Existence"](https://en.wikipedia.org/wiki/Proof_of_Existence) blockchain using the Substrate blockchain development framework.
This tutorial is aimed at someone who has never touched Substrate before, and wants to get a **basic** and **quick** understanding of what Substrate is all about. We will not be going too in depth about the intricacies of developing on Substrate, but will hopefully satisfy your curiosity so that you will continue this journey.
We predict that this tutorial will take you about **30 min to set up**, where you will not be actively doing anything, and about **1 hour of active participation** to complete. We will be using the [Rust programming language](https://www.rust-lang.org/) throughout this tutorial, but you do not need to know it to be able to complete this guide. We will provide you with working code snippets and explain what each line does at a high level.
We only expect that:
* You are generally familiar with software development and using the terminal
* You are generally familiar with blockchains and smart contract platforms
* You are open to learning about the bleeding edge of blockchain development.
It is important to emphasize again that Substrate is truly a bleeding edge framework. It is moving fast, and as a result, may sometimes break or cause issues. If you run into an issue on this tutorial, **we are here to help!**
You can [create a new issue](https://github.com/substrate-developer-hub/substrate-developer-hub.github.io/issues/new) or contact us directly on [Riot](https://riot.im/app/#/room/!HzySYSaIhtyWrwiwEV:matrix.org).
## What you will be doing
Before we even get started, let's layout what we are going to do over the course of this tutorial. We will:
1. Set up your computer to be able to develop on Substrate.
2. Use a template project to start running Substrate right away.
3. Modify this template project to add our own custom logic.
4. Use a pre-built front-end to interact with your brand new blockchain.
5. Review our initial implementation and iterate on it to start putting you in the mindset of a real Substrate blockchain developer.
Sound reasonable? Good, then let's begin!
## Setup
To develop on Substrate, your computer needs some prerequisites to establish a working development environment.
Things like [Rust](https://www.rust-lang.org/tools/install), [CMake](https://cmake.org/install/), [libssl](https://wiki.openssl.org/index.php/Libssl_API), [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git), etc...
If you are using a Unix based machine (Linux, MacOS), we have created a simple one-liner to get all of those prerequsites installed:
```bash
curl https://getsubstrate.io -sSf | bash -s -- --fast
```
> If you want to see specifically what this script does just visit: https://getsubstrate.io
If you are using Windows, the process is a little bit harder, but well documented [here](https://substrate.dev/docs/en/getting-started/installing-substrate#windows).
In addition to this, you will need all the basic tools for web development like `yarn`.
### Compiling Substrate
We have created a development package for Substrate, aptly named the [**Substrate Package**](https://github.com/substrate-developer-hub/substrate-package). This package will contain all the tools you need to complete this tutorial.
Unfortunately, the longest part of this setup process is actually compiling Substrate for the first time. To make things more efficient, follow these instructions to start the compilation process, then read the next section which will explain more about what is in the Substrate Package while things are compiling.
1. Clone the Substrate Package
```bash
git clone https://github.com/substrate-developer-hub/substrate-package
```
2. Initialize the Git submodules
```bash
cd substrate-package/
# This will load all the repositories used in the Substrate Package
git submodule update --init
```
3. Initialize your Wasm build environment
```bash
cd substrate-node-template/
# This will update rust nightly, add the Wasm32 build target, and install wasm-gc
./scripts/init.sh
```
4. Compile your Substrate node
```bash
cargo build --release
```
This final compilation will take approximately 15 minutes depending on your computer hardware. In that time, read the next section if you want to learn more about the contents of the Substrate Package.
---
# The Substrate Package
As we briefly mentioned above, the Substrate Package contains everything you need to start hacking on Substrate. More specifically it contains 3 different templates:
* [Substrate Module Template](https://github.com/substrate-developer-hub/substrate-module-template/)
* [Substrate Node Template](https://github.com/substrate-developer-hub/substrate-node-template/)
* [Substrate UI Template](https://github.com/substrate-developer-hub/substrate-ui-template/)
These templates are all individual git repositories, and work together to provide a cohesive set of tools for Substrate development.
[image here of all the parts coming together]
## Substrate Node Template
As you can see the Substrate Node Template sits at the center of this package.
A distributed blockchain system is composed of **nodes**, which is software that run on separate computers and communicate to one another forming a decentralized network.
The Substrate Node Template is an out-of-the-box working blockchain node built for easy modification. Without making any changes, you and your friends could share this node template and create a working blockchain network with a cryptocurrency and everything!
We will teach you how to use this node in "developer" mode, which allows you to run a network with a single node, and have some pre-configured user accounts with funds.
## Substrate Module Template
What makes Substrate so special is the ease at which you can compose the logic for your blockchain's underlying state transition function. This is _not_ the same as building smart contract's on top of modern blockchain systems. Whereas smart contracts are intentionally sandboxed from the internal workings of a blockchain, with Substrate, you have **full control** over how your blockchain operates.
[ image of smart contract versus module ]
We call this state transition function the **Substrate Runtime**, and it is composed of runtime modules. You can think of these runtime modules as individual pieces of logic which define what your blockchain can do! Substrate provides you with a number of pre-built runtime modules collected in the **Substrate Runtime Module Library** (SRML).
[ image of runtime composition ]
For example, the [Balances](https://substrate.dev/rustdocs/master/srml_balances/index.html) module controls the underlying currency of your blockchain by managing the _balance_ of all the accounts in your system. If you want to add smart contract functionality to your blockchain, you simply need to include the [Contracts](https://substrate.dev/rustdocs/master/srml_contracts/index.html) module. Even things like on-chain governance can be added to your blockchain by including modules like [Democracy](https://substrate.dev/rustdocs/master/srml_democracy/index.html), [Elections](https://substrate.dev/rustdocs/master/srml_elections/index.html), and [Collective](https://substrate.dev/rustdocs/master/srml_collective/index.html).
The goal of this tutorial is to teach you how to create your own Substrate Runtime Module which will be included in your custom blockchain!
## Substrate UI Template
Finally, to interact with your blockchain, we provide a simple [React](https://reactjs.org/) based user interface which uses the [**Polkadot.js API**](https://github.com/polkadot-js/api/). Even though this library is labeled "Polkadot", it is built to be flexible and work with any Substrate based chain, like the one we will have you build. This tutorial will not go into too much detail about building a custom UI, but we will have you interact with your blockchain using this.
# Proof Of Existence Chain
Let's talk about what you will be building in this tutorial. From [Wikipedia](https://en.wikipedia.org/wiki/Proof_of_Existence):
> Proof of Existence is an online service that verifies the existence of computer files as of a specific time via timestamped transactions in the bitcoin blockchain.
As mentioned, the Proof of Existence service was originally created on top of the Bitcoin blockchain. However, this functionality is [not properly supported](https://en.bitcoin.it/wiki/OP_RETURN) by the Bitcoin protocol, and the existing service uses more of a hack on top of other Bitcoin functions.
Introducing new functionality to a blockchain like Bitcoin is incredibly difficult since it is designed for a single
---
# Interacting with your Node
Now that your node has finished compiling, let's show you how everything works out of the box.
You need to open two terminal windows to run both your node and your UI:
1. Start your node:
```bash
cd substrate-node-template/
# Purge chain cleans up any old data from running a dev node before
cargo run --release -- purge-chain --dev
# Run your actual node in "developer" mode
cargo run --release -- --dev
```
You should see something like this if your node is running successfully:
```bash
$ cargo run --release -- --dev
2019-09-05 15:57:27 Running in --dev mode, RPC CORS has been disabled.
2019-09-05 15:57:27 Substrate Node
2019-09-05 15:57:27 version 2.0.0-b6bfc95-x86_64-macos
2019-09-05 15:57:27 by Anonymous, 2017, 2018
2019-09-05 15:57:27 Chain specification: Development
2019-09-05 15:57:27 Node name: unwieldy-skate-4685
2019-09-05 15:57:27 Roles: AUTHORITY
2019-09-05 15:57:27 Initializing Genesis block/state (state: 0x26bd…7093, header-hash: 0xbf06…58a9)
...
2019-09-05 15:57:30 Imported #1 (0x9f41…e673)
2019-09-05 15:57:32 Idle (0 peers), best: #1 (0x9f41…e673), finalized #1 (0x9f41…e673), ⬇ 0 ⬆ 0
2019-09-05 15:57:37 Idle (0 peers), best: #1 (0x9f41…e673), finalized #1 (0x9f41…e673), ⬇ 0 ⬆ 0
```
2. Start your UI:
```bash
cd substrate-front-end-template/
yarn install && yarn start
```
You should then be able to navigate to [`localhost:3000`](http://localhost:3000/) where you will see a simple UI and an increasing block number, showing that your Substrate node is running and connected to your UI!
If you look at the **Balances** component, you will see test accounts which you have access to. Some like Alice and Bob already have funds!
[ image ]
You can try to transfer some funds from Alice to Charlie using the **Transfer** component.
```
From: Alice
To: 5FLSigC9HGRKVhB9FiEo4Y3koPsNmBmLJbpXg2mp1hXcS59Y
Amount: 1000
```
[ image ]
If everything went successfully, you should see some notifications in the **Events** component, and of course Charlie's balance will now be `1000`.
Already you have a working blockchain, with an underlying cryptocurrency. You are able to make transfers easily with a simple, interactive UI.
Now let's build our own features!
> If you want to stop your node or UI, you can press `ctrl + c`.
---
# Adding A Custom Runtime Module
We will now modify the Substrate Node Template to introduce the basic functionality of a Proof Of Existence blockchain.
Open the `substrate-node-template` folder of the Substrate Package in your favorite code editor. Then open the file at `runtime/src/template.rs`
You will see some pre-written code which acts as a template for an embedded Substrate Runtime Module. You can delete the contents of this file since we will start from scratch for full transparency.
At a high level, the a Substrate Runtime Module can be broken down into 5 sections:
```rust
// 1. Imports
use support::{decl_module, decl_storage, decl_event,...};
// 2. Module Configuration
pub trait Trait: system::Trait {...}
// 3. Module Events
decl_event! {...}
// 4. Module Storage Items
decl_storage! {...}
// 5. Callable Module Functions
decl_module! {...}
```
Things like events, storage, and callable functions should look familiar to you if you have done other blockchain development. We will show you what each of these components look like for a basic Proof Of Existence blockchain.
## Imports
Since imports are pretty boring, you can start by copying this at the top of your empty `template.rs` file:
```rust
use support::{decl_module, decl_storage, decl_event, ensure, StorageMap};
use rstd::vec::Vec;
use system::ensure_signed;
```
## Module Configuration
For now, the only thing we will configure about our module is that it will emit some Events.
```rust
/// The module's configuration trait.
pub trait Trait: system::Trait {
/// The overarching event type.
type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;
}
```
Will come back to this configuration trait later in the tutorial when we continue to iterate on the Proof Of Existence design.
## Module Events
Since we configured our module to emit events, let's go ahead and define that!
```rust
// This module's events.
decl_event!(
pub enum Event<T> where AccountId = <T as system::Trait>::AccountId {
// Event emitted when a proof has been stored into chain storage
ProofStored(AccountId, Vec<u8>),
// Event emitted when a proof has been erased from chain storage
ProofErased(AccountId, Vec<u8>),
}
);
```
Our module will only have two events:
1. When a new proof is added to the blockchain.
2. When a proof is removed.
The events can contain some metadata, in this case, each event will also display who triggered the event (`AccountId`), and the proof data (`Vec<u8>`) that is being stored or removed.
## Module Storage Items
To add a new proof to the blockchain, we will simply store that proof in our module's storage. To store that value, we will create a [hash map](https://en.wikipedia.org/wiki/Hash_table) from the proof to the owner of that proof.
```rust
// This module's storage items.
decl_storage! {
trait Store for Module<T: Trait> as PoeStorage {
// Define a 'Proofs' storage item for a map with
// the proof digest as the key, and associated AccountId as value.
// The 'get(proofs)' is the default getter.
Proofs get(proofs): map Vec<u8> => T::AccountId;
}
}
```
If a proof has an owner, then we know that it has been claimed! Otherwise, the proof is still available to be claimed.
## Callable Module Functions
As implied by our Module Events, we will have two functions the user can call in this Substrate Runtime Module:
1. `store_proof()`: Allow a user to claim an unclaimed proof.
2. `erase_proof()`: Allow the owner of a proof to erase their claim.
Here is what that implementation looks like:
```rust
// The module's dispatchable functions.
decl_module! {
/// The module declaration.
pub struct Module<T: Trait> for enum Call where origin: T::Origin {
// A default function for depositing events
fn deposit_event() = default;
// Allow a user to store an unclaimed proof
fn store_proof(origin, digest: Vec<u8>) {
// Verify that the incoming transaction is signed
let sender = ensure_signed(origin)?;
// Verify that the specified proof has not been claimed yet
ensure!(!Proofs::<T>::exists(&digest), "This proof has already been claimed");
// Store the proof and the claim owner
Proofs::<T>::insert(&digest, sender.clone());
// Emit an event that the claim was stored
Self::deposit_event(RawEvent::ProofStored(sender, digest));
}
// Allow the owner of a proof to erase their claim
fn erase_proof(origin, digest: Vec<u8>) {
// Determine who is calling the function
let sender = ensure_signed(origin)?;
// Verify that the specified proof has been claimed
ensure!(Proofs::<T>::exists(&digest), "This proof has not been stored yet");
// Get owner of the claim
let owner = Self::proofs(&digest);
// Verify that sender of the current call is the claim owner
ensure!(sender == owner, "You must own this proof to erase it");
// Remove claim from storage
Proofs::<T>::remove(&digest);
// Emit an event that the claim was erased
Self::deposit_event(RawEvent::ProofErased(sender, digest));
}
}
}
```
There is some funny Rust syntax in here like `<T>`, `&`, `?`, etc... For the purposes of this tutorial, we will not go into these details, but the individual parts of the function should make sense, especially with the code comments.
## Compile Your New Module
If you were able to copy all of the parts of this module correctly into your `template.rs` file, you should be able to recompile your node successfully!
```bash
cargo build --release
```
---
# Testing Your New Blockchain