From 822bde77c954ce00731f4a7e1e7dc085f0857017 Mon Sep 17 00:00:00 2001 From: Ivan Kuznetsov Date: Tue, 15 Aug 2017 14:20:34 +0700 Subject: [PATCH] Implement basic blocks --- main.go | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 50 insertions(+), 2 deletions(-) diff --git a/main.go b/main.go index a075e6d..8c4933c 100644 --- a/main.go +++ b/main.go @@ -1,7 +1,55 @@ package main -import "fmt" +import ( + "crypto/sha256" + "fmt" + "log" + "strconv" + "time" +) + +// Block keeps block headers +type Block struct { + Timestamp int64 + Data []byte + PrevBlock []byte + hash []byte +} + +// SetHash calculates and sets block hash +func (b *Block) SetHash() { + h := sha256.New() + timestamp := []byte(strconv.FormatInt(b.Timestamp, 10)) + var data []byte + data = append(data, b.PrevBlock...) + data = append(data, b.Data...) + data = append(data, timestamp...) + + _, err := h.Write(data) + if err != nil { + log.Panic(err) + } + b.hash = h.Sum(nil) +} + +// NewBlock creates and returns Block +func NewBlock(data string, prevBlock []byte) *Block { + block := &Block{time.Now().Unix(), []byte(data), prevBlock, []byte("")} + block.SetHash() + return block +} + +// NewGenesisBlock creates and returns genesis Block +func NewGenesisBlock() *Block { + return NewBlock("Genesis Block", []byte("0")) +} func main() { - fmt.Println("Blockchain") + gb := NewGenesisBlock() + b1 := NewBlock("Send 1 BTC to Ivan", gb.hash) + + fmt.Printf("%s\n", gb.Data) + fmt.Printf("%x\n", gb.hash) + fmt.Printf("%s\n", b1.Data) + fmt.Printf("%x\n", b1.hash) }