Browse Source

Use strings as hash -> better encoding

gRPC
garritfra 6 years ago
parent
commit
73614b0482
  1. 25
      core/Block.go
  2. 4
      core/Blockchain.go
  3. 11
      core/Server.go
  4. 1
      core/Transaction.go

25
core/Block.go

@ -11,21 +11,13 @@ import (
// Block Struct
type Block struct {
Timestamp time.Time
Hash []byte
PreviousHash []byte
Data interface{}
}
// BlockJSON is a modified Block struct for json representation
type BlockJSON struct {
Timestamp time.Time
Hash string
PreviouseHash string
Data interface{}
Hash string
PreviousHash string
Data []Transaction
}
// NewBlock creates a new Block
func NewBlock(previousHash []byte, data interface{}) Block {
func NewBlock(previousHash string, data []Transaction) Block {
block := Block{Timestamp: time.Now(), PreviousHash: previousHash, Data: data}
block.calculateHash()
@ -43,12 +35,7 @@ func (block *Block) calculateHash() {
bytes := buffer.Bytes()
hasher.Write(bytes)
sum := hasher.Sum(nil)
block.Hash = sum
}
sum := hex.EncodeToString(hasher.Sum(nil))
// EncodeJSON encodes a Block to a JSON representable struct
func (block *Block) EncodeJSON() BlockJSON {
return BlockJSON{Timestamp: block.Timestamp, PreviouseHash: hex.EncodeToString(block.PreviousHash), Hash: hex.EncodeToString(block.Hash), Data: block.Data}
block.Hash = string(sum)
}

4
core/Blockchain.go

@ -21,6 +21,8 @@ func NewBlockchain() Blockchain {
}
func generateGenesisBlock() Block {
block := NewBlock([]byte{}, []byte("Genesis"))
transaction := Transaction{Amount: 0, Sender: "0", Receiver: "0", Message: "Genesis"}
block := NewBlock("0", []Transaction{transaction})
return block
}

11
core/Server.go

@ -17,7 +17,7 @@ func StartServer() {
blockchain = NewBlockchain()
transaction := Transaction{Sender: "foo", Receiver: "bar", Amount: 100}
block := NewBlock(blockchain.blocks[0].Hash, transaction)
block := NewBlock(blockchain.blocks[0].Hash, []Transaction{transaction})
blockchain.addBlock(block)
http.HandleFunc("/blockchain", listBlocks)
@ -28,12 +28,5 @@ func StartServer() {
}
func listBlocks(w http.ResponseWriter, r *http.Request) {
var jsonBlocks []BlockJSON
for _, block := range blockchain.blocks {
jsonBlocks = append(jsonBlocks, block.EncodeJSON())
}
json.NewEncoder(w).Encode(jsonBlocks)
json.NewEncoder(w).Encode(blockchain.blocks)
}

1
core/Transaction.go

@ -5,4 +5,5 @@ type Transaction struct {
Sender string
Receiver string
Amount int
Message string
}

Loading…
Cancel
Save