diff --git a/core/Block.go b/core/Block.go index dceb234..9d059fb 100644 --- a/core/Block.go +++ b/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} } diff --git a/core/Blockchain.go b/core/Blockchain.go index f239f58..deeb576 100644 --- a/core/Blockchain.go +++ b/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 } diff --git a/server/webserver.go b/server/webserver.go index f48e418..6903cc3 100644 --- a/server/webserver.go +++ b/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) {