Skip to content

#5.1 Why can't I use Blockchain for data?  #2

Description

@achievermina

main.go


package main

import (
	"html/template"
	"log"
	"net/http"

	Blockchain "github.com/achievermina/gocoin/blockchain"
)

const port string = ":8000"

type data struct {
	Blocks *Blockchain // I tried to use Blockchain instead of block[]. I have an error here. Can you let me know why? @serranoarevalo 
}

func home(rw http.ResponseWriter, r *http.Request) {
	tmpl := template.Must(template.ParseFiles("templates/home.gohtml"))
	data := data{Blockchain.GetBlockchain()}
	tmpl.Execute(rw, data)
}

func main() {
	chain := Blockchain.GetBlockchain()
	chain.AddBlock("Second")
	chain.AddBlock("Third Block")

	http.HandleFunc("/", home)
	log.Fatal(http.ListenAndServe(port, nil))
}

blockchain.go

package blockchain

import (
	"crypto/sha256"
	"fmt"
	"sync"
)

type Block struct {
	Data string
	Hash string
	PrevHash string
}

type Blockchain struct {
	Blocks []*Block
}

var b *Blockchain
var once sync.Once

func createBlock(data string) *Block {
	newBlock := Block{data, "", b.getLastHash()}
	newBlock.createHash()
	return &newBlock
}

func GetBlockchain() *Blockchain {
	if b == nil {
		once.Do(func () {
			b = &Blockchain{}
			b.Blocks = append(b.Blocks, createBlock("First Block"))
		})
	}
	return b;
}

func (b* Block) createHash() {
	hash := sha256.Sum256([]byte(b.Data + b.PrevHash))
	b.Hash = fmt.Sprintf("%x", hash)
}

func (b* Blockchain) getLastHash() string {
	if (len(b.Blocks) > 0 ) {
		return b.Blocks[len(b.Blocks)-1].Hash 
	}
	return ""
}

func (b* Blockchain) AddBlock(data string) {
	b.Blocks = append(b.Blocks, createBlock(data))
}

func(b* Blockchain) PrintBlocks() {
	for _, Block := range b.Blocks {
		fmt.Printf("Data: %s \n", Block.Data)
		fmt.Printf("Hash: %s \n", Block.Hash)
		fmt.Printf("PrevHash: %s \n", Block.PrevHash)
	}
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions