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
- Refer to my simple-webserver-with-REST for the webserver engine
- Refer to my cheat sheet on blockchains
- I got a lot of inspiration from here
Gorilla/mux is a popular router I use for the webserver.
go get -v -u github.com/gorilla/mux
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,
go run single-node-blockchain-with-REST.go \
guts.go blockchain.go blockchain-interface.go \
router.go routes.go handlers.go logger.go
Then you can goto the webpage to see your first block,
You could also use curl from the command line,
curl localhost:1234
curl localhost:1234/showblock/0
curl -H "Content-Type: application/json" \
-X POST \
-d '{"data":"Add this data for new block"}' \
localhost:1234/addblock
Check,
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()