Implement basic blocks

This commit is contained in:
Ivan Kuznetsov 2017-08-15 14:20:34 +07:00
parent 6f3810242b
commit 822bde77c9
1 changed files with 50 additions and 2 deletions

52
main.go
View File

@ -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)
}