Skip to content

Commit

Permalink
added consensus algorism
Browse files Browse the repository at this point in the history
  • Loading branch information
jagottsicher committed Feb 23, 2024
1 parent 3890804 commit 6c09fb7
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 18 deletions.
8 changes: 4 additions & 4 deletions blockchain/block.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,10 @@ func (b *Block) MarshalJSON() ([]byte, error) {
func (b *Block) UnmarshalJSON(data []byte) error {
var previousHash string
v := &struct {
Timestamp *int64 `json: "timestamp"`
Nonce *int `json: "nonce"`
PreviousHash *string `json: "previous_hash"`
Transactions *[]*Transaction `json: "transactions"`
Timestamp *int64 `json:"timestamp"`
Nonce *int `json:"nonce"`
PreviousHash *string `json:"previous_hash"`
Transactions *[]*Transaction `json:"transactions"`
}{
Timestamp: &b.timestamp,
Nonce: &b.nonce,
Expand Down
39 changes: 26 additions & 13 deletions blockchain/blockchain.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ func (bc *Blockchain) Chain() []*Block {

func (bc *Blockchain) Run() {
bc.StartSyncNeighbors()
bc.ResolveConflicts()
// bc.StartMining()
}

func (bc *Blockchain) SetNeightbors() {
Expand Down Expand Up @@ -98,6 +100,18 @@ func (bc *Blockchain) MarshalJSON() ([]byte, error) {
})
}

func (bc *Blockchain) UnmarshalJSON(data []byte) error {
v := &struct {
Blocks *[]*Block `json:"chain"`
}{
Blocks: &bc.chain,
}
if err := json.Unmarshal(data, &v); err != nil {
return err
}
return nil
}

func (bc *Blockchain) CreateBlock(nonce int, previousHash [32]byte) *Block {
b := NewBlock(nonce, previousHash, bc.transactionPool)
bc.chain = append(bc.chain, b)
Expand Down Expand Up @@ -228,6 +242,17 @@ func (bc *Blockchain) Mining() bool {
previousHash := bc.LastBlock().Hash()
bc.CreateBlock(nonce, previousHash)
log.Println("action=mining, status=success")

for _, n := range bc.neighbors {
endpoint := fmt.Sprintf("http://%s/consensus", n)
client := &http.Client{}
req, _ := http.NewRequest("PUT", endpoint, nil)
resp, err := client.Do(req)
if err != nil {
log.Printf("%v", resp)
}
}

return true
}

Expand Down Expand Up @@ -298,7 +323,7 @@ func (bc *Blockchain) ResolveConflicts() bool {
log.Printf("Resolved conflicts: blockchain was replaced")
return true
}
log.Printf("Resolved conflicts: blockchain was nor replaced")
log.Printf("Resolved conflicts: blockchain was not replaced")
return false
}

Expand All @@ -313,15 +338,3 @@ func (ar *AmountResponse) MarshalJSON() ([]byte, error) {
Amount: ar.Amount,
})
}

func (bc *Blockchain) UnmarshalJSON(data []byte) error {
v := &struct {
Blocks *[]*Block `json: "chain"`
}{
Blocks: &bc.chain,
}
if err := json.Unmarshal(data, &v); err != nil {
return err
}
return nil
}
19 changes: 19 additions & 0 deletions blockchain_node/blockchain_node.go
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,24 @@ func (bcn *BlockchainNode) Amount(w http.ResponseWriter, r *http.Request) {
}
}

func (bcn *BlockchainNode) Consensus(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodPut:
bc := bcn.GetBlockchain()
replaced := bc.ResolveConflicts()

w.Header().Add("Content-Type", "application/json")
if replaced {
io.WriteString(w, string(utils.JsonStatus("success")))
} else {
io.WriteString(w, string(utils.JsonStatus("fail")))
}
default:
log.Printf("ERROR: Invalid HTTP method")
w.WriteHeader(http.StatusBadRequest)
}
}

func (bcn *BlockchainNode) Run() {
bcn.GetBlockchain().Run()

Expand All @@ -200,6 +218,7 @@ func (bcn *BlockchainNode) Run() {
http.HandleFunc("/mine", bcn.Mine)
http.HandleFunc("/mine/start", bcn.StartMine)
http.HandleFunc("/amount", bcn.Amount)
http.HandleFunc("/consensus", bcn.Consensus)

log.Fatal(http.ListenAndServe("0.0.0.0:"+strconv.Itoa(int(bcn.Port())), nil))
}
2 changes: 1 addition & 1 deletion utils/neighbors.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ func IsFoundNode(host string, port uint16) bool {

_, err := net.DialTimeout("tcp", target, 1*time.Second)
if err != nil {
fmt.Printf("%s %v\n", target, err)
// fmt.Printf("%s %v\n", target, err)
return false
}
return true
Expand Down

0 comments on commit 6c09fb7

Please sign in to comment.