Shawn Tabrizi
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # 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

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully