Browse Source

Add JSON structure for dynamic hash

now.sh
garritfra 5 years ago
parent
commit
8c0600e5e7
  1. 24
      core/Block.go
  2. 27
      core/Blockchain.go
  3. 2
      server/webserver.go

24
core/Block.go

@ -2,13 +2,33 @@ package core
import (
"time"
"github.com/garritfra/blockchain-project/crypto"
)
// Block Struct
type Block struct {
Timestamp time.Time
Hash string
PreviousHash string
Data []Transaction
Nonce int
Proof int
}
// JSONBlock representation
type JSONBlock struct {
Timestamp time.Time `json:"timestamp"`
Hash string `json:"hash"`
PreviousHash string `json:"previous_hash"`
Data []Transaction `json:"data"`
Proof int `json:"nonce"`
}
// Hash returns the hash of the block
func (block *Block) Hash() string {
return crypto.CalculateHash(block)
}
// AsJSON is needed, because the field `hash` is calculated dynamically, and cannot be presented in the standard `Block` struct
func (block *Block) AsJSON() JSONBlock {
return JSONBlock{Timestamp: block.Timestamp, Hash: block.Hash(), PreviousHash: block.PreviousHash, Data: block.Data, Proof: block.Proof}
}

27
core/Blockchain.go

@ -4,8 +4,6 @@ import (
"log"
"strings"
"time"
"github.com/garritfra/blockchain-project/crypto"
)
// Blockchain struct
@ -23,9 +21,7 @@ func (bc *Blockchain) MineBlock() Block {
// Mine Block
log.Print("Mining Block...")
for {
hash := crypto.CalculateHash(block)
if strings.HasPrefix(hash, "00000") {
block.Hash = hash
if strings.HasPrefix(block.Hash(), "00000") {
bc.Blocks = append(bc.Blocks, block)
bc.PendingTransactions = []Transaction{}
@ -33,7 +29,7 @@ func (bc *Blockchain) MineBlock() Block {
log.Print("Block Added: ", block.Hash)
return block
}
block.Nonce++
block.Proof++
}
}
@ -63,5 +59,22 @@ func (bc *Blockchain) GetLastHash() string {
if bcLength == 0 {
return "0"
}
return bc.Blocks[len(bc.Blocks)-1].Hash
return bc.Blocks[len(bc.Blocks)-1].Hash()
}
// JSONBlockchain is needed, because the hash of each block is calculated dynamically, and therefore is not stored in the `Block` struct
type JSONBlockchain struct {
Blocks []JSONBlock
PendingTransactions []Transaction
}
// AsJSON returns the Blockchain as a JSON Blockchain
func (bc *Blockchain) AsJSON() JSONBlockchain {
jsonChain := JSONBlockchain{PendingTransactions: bc.PendingTransactions}
for _, block := range bc.Blocks {
jsonChain.Blocks = append(jsonChain.Blocks, block.AsJSON())
}
return jsonChain
}

2
server/webserver.go

@ -40,7 +40,7 @@ func handleError(err error, w http.ResponseWriter, r *http.Request) {
}
func handleListBlocks(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(blockchain.Blocks)
json.NewEncoder(w).Encode(blockchain.AsJSON().Blocks)
}
func handleAddTransaction(w http.ResponseWriter, r *http.Request) {

Loading…
Cancel
Save