Browse Source

Add Block

golang
garritfra 6 years ago
parent
commit
7f7a72632a
  1. 36
      Block.go
  2. 14
      Blockchain.go
  3. 17
      main.go

36
Block.go

@ -1,6 +1,38 @@
package main
import (
"bytes"
"crypto/sha256"
"encoding/gob"
"time"
)
// Block Struct
type Block struct {
hash []byte
previousHash []byte
Timestamp time.Time
Hash []byte
PreviousHash []byte
}
func newBlock(previousHash []byte) Block {
block := Block{Timestamp: time.Now(), PreviousHash: previousHash}
block.calculateHash()
return block
}
func (block *Block) calculateHash() {
var buffer bytes.Buffer
encoder := gob.NewEncoder(&buffer)
if err := encoder.Encode(block); err != nil {
panic(err)
}
hasher := sha256.New()
bytes := buffer.Bytes()
hasher.Write(bytes)
sum := hasher.Sum(nil)
block.Hash = sum
}

14
Blockchain.go

@ -1,10 +1,5 @@
package main
import (
"crypto/sha256"
"fmt"
)
// Blockchain struct
type Blockchain struct {
blocks []Block
@ -25,11 +20,6 @@ func newBlockchain() Blockchain {
}
func generateGenesisBlock() Block {
block := new(Block)
hasher := sha256.New()
s := fmt.Sprintf("%v", block)
sum := hasher.Sum([]byte(s))
block.hash = sum
return *block
block := newBlock([]byte{})
return block
}

17
main.go

@ -1,14 +1,27 @@
package main
import (
"encoding/hex"
"fmt"
)
func main() {
blockchain := newBlockchain()
for _, v := range blockchain.blocks {
fmt.Println(v.hash)
block := newBlock(blockchain.blocks[0].Hash)
blockchain.addBlock(block)
block = newBlock(blockchain.blocks[1].Hash)
blockchain.addBlock(block)
for i := 0; i < len(blockchain.blocks); i++ {
block := blockchain.blocks[i]
fmt.Println("Block " + string(i))
fmt.Println(hex.EncodeToString(block.PreviousHash))
fmt.Println(hex.EncodeToString(block.Hash))
fmt.Println(block.Timestamp)
fmt.Println()
}
}

Loading…
Cancel
Save