single-node-blockchain-with-REST example
A simple single node sha256 blockchain with a REST JSON API
(to view (GET) the blockchain and add (POST) a block).
Table of Contents,
Documentation and reference,
GitHub Webpage
PREREQUISITES
Gorilla/mux is a popular router I use for the webserver.
go get -v -u github.com/gorilla/mux
OVERVIEW
This code is broken up into three parts,
- guts The blockchain code
- blockchain-interface The interface to the blockchain
- Webserver The API and gui
This examples will,
- Create a Blockchain
- Hash a Block
- View the Entire Blockchain via a web GUI
- View a specific Block via a REST API
- Add a Block (with your data) to the chain via a REST API
This illustration may help,
RUN
go run single-node-blockchain-with-REST.go \
guts.go blockchain.go blockchain-interface.go \
router.go routes.go handlers.go logger.go
GET (View the entire Blockchain)
Then you can goto the webpage to see your first block,
localhost:1234/
You could also use curl from the command line,
curl localhost:1234
GET (Show a Particular Block)
localhost:1234//showblock/0
curl localhost:1234/showblock/0
POST (Add a Block)
curl -H "Content-Type: application/json" \
-X POST \
-d '{"data":"Add this data for new block"}' \
localhost:1234/addblock
Check,
localhost:1234/
HOW IT WORKS
We will just be looking at the guts, ignoring the webserver and blockchain-interface.
So it actually becomes quite simple. A Block is just a struct and The Blockchain
is simply a slice of structs. That's it.
type BlockStruct struct {
Index int `json:"index"`
Timestamp string `json:"timestamp"`
Data string `json:"data"`
Hash string `json:"hash"`
PrevHash string `json:"prevhash"`
}
type BlockchainSlice []BlockStruct
var Blockchain = BlockchainSlice{}
And guts.go
contain the three basic things you want to do
to that Blockchain (slice of structs),
- calculateBlockHash()
- isBlockValid()
- createNewBlock()