├── README.md ├── _config.yml ├── go.mod └── main.go /README.md: -------------------------------------------------------------------------------- 1 | # Golang Blockchain 2 | 3 | ### In this tutorial, we look at the go module system and build the basic framework for a blockchain. 4 | 5 | ## Run `go run main.go` to run the app, run `go build main.go` to build an executable file. 6 | 7 | ### Check out the Youtube Tutorial for this [Go Program](https://youtu.be/mYlHT9bB6OE). Here is our [Youtube Channel](https://www.youtube.com/channel/UCYqCZOwHbnPwyjawKfE21wg) Subscribe for more content. 8 | 9 | ### Check out our blog at [tensor-programming.com](http://tensor-programming.com/). 10 | 11 | ### Our [Twitter](https://twitter.com/TensorProgram), our [facebook](https://www.facebook.com/Tensor-Programming-1197847143611799/) and our [Steemit](https://steemit.com/@tensor). 12 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-midnight -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/tensor-programming/golang-blockchain 2 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "crypto/sha256" 6 | "fmt" 7 | ) 8 | 9 | type BlockChain struct { 10 | blocks []*Block 11 | } 12 | 13 | type Block struct { 14 | Hash []byte 15 | Data []byte 16 | PrevHash []byte 17 | } 18 | 19 | func (b *Block) DeriveHash() { 20 | info := bytes.Join([][]byte{b.Data, b.PrevHash}, []byte{}) 21 | hash := sha256.Sum256(info) 22 | b.Hash = hash[:] 23 | } 24 | 25 | func CreateBlock(data string, prevHash []byte) *Block { 26 | block := &Block{[]byte{}, []byte(data), prevHash} 27 | block.DeriveHash() 28 | return block 29 | } 30 | 31 | func (chain *BlockChain) AddBlock(data string) { 32 | prevBlock := chain.blocks[len(chain.blocks)-1] 33 | new := CreateBlock(data, prevBlock.Hash) 34 | chain.blocks = append(chain.blocks, new) 35 | } 36 | 37 | func Genesis() *Block { 38 | return CreateBlock("Genesis", []byte{}) 39 | } 40 | 41 | func InitBlockChain() *BlockChain { 42 | return &BlockChain{[]*Block{Genesis()}} 43 | } 44 | 45 | func main() { 46 | chain := InitBlockChain() 47 | 48 | chain.AddBlock("First Block after Genesis") 49 | chain.AddBlock("Second Block after Genesis") 50 | chain.AddBlock("Third Block after Genesis") 51 | 52 | for _, block := range chain.blocks { 53 | fmt.Printf("Previous Hash: %x\n", block.PrevHash) 54 | fmt.Printf("Data in Block: %s\n", block.Data) 55 | fmt.Printf("Hash: %x\n", block.Hash) 56 | } 57 | } 58 | --------------------------------------------------------------------------------