Skip to content

Commit

Permalink
Merge branch 'feature-branch' into DEPLOY-front-end
Browse files Browse the repository at this point in the history
  • Loading branch information
elarsaks committed Aug 3, 2023
2 parents 09d32b2 + 5c0f098 commit 09f2c58
Show file tree
Hide file tree
Showing 10 changed files with 84 additions and 30 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/deploy-front-end.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
name: Full Stack Deployment
name: Delpoy front-end

on:
push:
Expand Down Expand Up @@ -31,7 +31,7 @@ jobs:
- name: Install dependencies
run: |
cd cmd/react_dashboard
npm ci
npm i
- name: Build
run: |
Expand Down
3 changes: 3 additions & 0 deletions cmd/blockchain_server/handlers/consensus.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package handlers

import (
"fmt"
"io"
"log"
"net/http"
Expand All @@ -12,6 +13,8 @@ import (

// Resolve the conflicts in the BlockchainServer
func (h *BlockchainServerHandler) Consensus(w http.ResponseWriter, req *http.Request) {
fmt.Println("CALL CONSENSUS")

switch req.Method {
case http.MethodPut:
bc := h.server.GetBlockchain()
Expand Down
2 changes: 1 addition & 1 deletion cmd/blockchain_server/handlers/register_wallet.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func (h *BlockchainServerHandler) RegisterWallet(w http.ResponseWriter, req *htt
}

// Call RegisterNewWallet to register the provided wallet address
success := h.server.GetBlockchain().RegisterNewWallet(requestBody.BlockchainAddress, "Register User Wallet")
success := h.server.GetBlockchain().RegisterNewWallet(requestBody.BlockchainAddress, "REGISTER USER WALLET")
if !success {
log.Println("ERROR: Failed to register wallet")
w.WriteHeader(http.StatusInternalServerError)
Expand Down
2 changes: 1 addition & 1 deletion cmd/blockchain_server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ func (bcs *BlockchainServer) Run() {
handler := handlers.NewBlockchainServerHandler(bcs)

// Define routes
router.HandleFunc("/", handler.GetChain)
router.HandleFunc("/chain", handler.GetChain)
router.HandleFunc("/balance", handler.Balance)
router.HandleFunc("/consensus", handler.Consensus)
router.HandleFunc("/mine", handler.Mine)
Expand Down
Binary file added cmd/react_dashboard/public/go-blockchain.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion cmd/react_dashboard/public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Go Blockchain</title>
<meta property="og:image" content="%PUBLIC_URL%/go_blockchain.png" />
<meta property="og:image" content="%PUBLIC_URL%/go-blockchain.png" />
<meta property="og:title" content="Go Blockchain" />
<meta property="og:description" content="Blockchain built using Golang, React and Docker" />
<meta property="og:url" content="https://elarsaks.github.io/Go-blockchain/" />
Expand Down
2 changes: 1 addition & 1 deletion cmd/react_dashboard/src/components/wallet/Wallet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ const Wallet: React.FC<WalletProps> = ({ type }) => {

const sendCrypto = () => {
transaction({
message: "Transaction from React.",
message: "USER TRANSACTION",
recipientBlockchainAddress: walletDetails.recipientAddress,
senderBlockchainAddress: walletDetails.blockchainAddress,
senderPrivateKey: walletDetails.privateKey,
Expand Down
7 changes: 5 additions & 2 deletions pkg/block/block.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,14 @@ const (

BLOCKCHAIN_PORT_RANGE_START = 5001
BLOCKCHAIN_PORT_RANGE_END = 5003
NEIGHBOR_IP_RANGE_START = 1
NEIGHBOR_IP_RANGE_END = 3
NEIGHBOR_IP_RANGE_START = 1 // This is default IP range for Docker containers
NEIGHBOR_IP_RANGE_END = 254 // Docker used bridge network, as a default
BLOCKCHIN_NEIGHBOR_SYNC_TIME_SEC = 20
)

// TODO: Hold neighbours in a blockchain_server, so they can be updated
// var NEIGHBORS = []string{"http://miner-1:5001", "http://miner-2:5002", "http://miner-3:5003"}

// Definition of the Block type
type Block struct {
timestamp int64
Expand Down
80 changes: 62 additions & 18 deletions pkg/block/blockchain.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,20 @@ func (bc *Blockchain) Run() {

// Find neighbors of the Blockchain
func (bc *Blockchain) SetNeighbors() {
bc.neighbors = utils.FindNeighbors(
utils.GetHost(), bc.port,
NEIGHBOR_IP_RANGE_START, NEIGHBOR_IP_RANGE_END,
BLOCKCHAIN_PORT_RANGE_START, BLOCKCHAIN_PORT_RANGE_END)
log.Printf("%v", bc.neighbors)

bc.neighbors = []string{
"http://miner-1:5001",
"http://miner-2:5002",
"http://miner-3:5003",
}

/*
bc.neighbors = utils.FindNeighbors(
utils.GetHost(), bc.port,
NEIGHBOR_IP_RANGE_START, NEIGHBOR_IP_RANGE_END,
BLOCKCHAIN_PORT_RANGE_START, BLOCKCHAIN_PORT_RANGE_END)*/

// log.Printf("%v", bc.neighbors)
}

// Sync neighbors of the Blockchain
Expand Down Expand Up @@ -249,10 +258,6 @@ func (bc *Blockchain) VerifyTransactionSignature(

log.Println("Validate signature", string(m))

// Print out the transaction
// fmt.Println("Verify TransactionSignature")
// fmt.Printf("%v\n", string(m[:]))

h := sha256.Sum256([]byte(m))
return ecdsa.Verify(senderPublicKey, h[:], s.R, s.S)
}
Expand Down Expand Up @@ -320,11 +325,15 @@ func (bc *Blockchain) Mining() bool {
bc.CreateBlock(nonce, previousHash)

// Log a successful mining operation
// log.Println("action=mining, status=success")
// #debug
log.Println("action=mining, status=success")

// Send a consensus request to each neighbor
for _, n := range bc.neighbors {
endpoint := fmt.Sprintf("http://%s/consensus", n)

fmt.Println("Send consensus to neigbour ", n)

endpoint := fmt.Sprintf("%s/consensus", n)
client := &http.Client{}
req, _ := http.NewRequest("PUT", endpoint, nil)
resp, err := client.Do(req)
Expand Down Expand Up @@ -357,6 +366,9 @@ func (bc *Blockchain) RegisterNewWallet(blockchainAddress string, message string
return false
}

// Mine a new block when the wallet is registered successfully
bc.StartMining()

// Return true indicating the wallet was registered successfully
return true
}
Expand Down Expand Up @@ -415,33 +427,65 @@ func (bc *Blockchain) ValidChain(chain []*Block) bool {
return true
}

// Resolve conflicts
// ResolveConflicts resolves conflicts in the blockchain by checking the chains of its neighbors
// and replacing its own chain with the longest valid chain found.
func (bc *Blockchain) ResolveConflicts() bool {
// Initialize variables to track the longest chain and its length
var longestChain []*Block = nil
maxLength := len(bc.chain)

// Iterate over the neighbors to fetch their chains
for _, n := range bc.neighbors {
endpoint := fmt.Sprintf("http://%s/chain", n)
resp, _ := http.Get(endpoint)
if resp.StatusCode == 200 {
fmt.Println("Resolve conflict with ", n)

// Construct the endpoint URL to fetch the chain from the neighbor
endpoint := fmt.Sprintf("%s/chain", n)

// Send an HTTP GET request to the neighbor's endpoint to fetch their chain
resp, err := http.Get(endpoint)
if err != nil {

// Log any error that occurred while fetching the chain
log.Printf("ERROR: Failed to fetch chain from neighbor %s: %v", n, err)
continue // Skip to the next neighbor in case of error
}

// Check the response status code to see if the request was successful
if resp.StatusCode == http.StatusOK {
var bcResp Blockchain
decoder := json.NewDecoder(resp.Body)
_ = decoder.Decode(&bcResp)

// Decode the JSON response into a Blockchain object
err := decoder.Decode(&bcResp)
if err != nil {
// Log any error that occurred during JSON decoding
log.Printf("ERROR: Failed to decode JSON response from neighbor %s: %v", n, err)
continue // Skip to the next neighbor in case of error
}

// Get the chain from the neighbor's Blockchain object
chain := bcResp.Chain()

// Check if the fetched chain is longer than the current longest chain
// and if it is a valid chain using bc.ValidChain()
if len(chain) > maxLength && bc.ValidChain(chain) {
maxLength = len(chain)
longestChain = chain
}
} else {
// Log the status code if the request to the neighbor's endpoint was not successful
log.Printf("WARNING: Failed to fetch chain from neighbor %s. Status code: %d", n, resp.StatusCode)
}
}

// If a longer valid chain was found, replace the blockchain's chain with it
if longestChain != nil {
bc.chain = longestChain
log.Printf("Resovle confilicts replaced")
log.Printf("INFO: Resolved conflicts. Replaced blockchain with the longest valid chain.")
return true
}
log.Printf("Resovle conflicts not replaced")

// If no longer valid chain was found, log and return false
log.Printf("INFO: No longer valid chain found among neighbors. No conflicts resolved.")
return false
}
12 changes: 8 additions & 4 deletions pkg/utils/neighbor.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,15 @@ func FindNeighbors(myHost string, myPort uint16, startIp uint8, endIp uint8, sta
prefixHost := m[1]
lastIp, _ := strconv.Atoi(m[len(m)-1])
neighbors := make([]string, 0)
// neighbors = []string{"http://miner-1:5001", "http://miner-2:5002", "http://miner-3:5003"}

fmt.Printf("Finding neighbors for %s\n", address)
for port := startPort; port <= endPort; port += 1 {
for ip := startIp; ip <= endIp; ip += 1 {
guessHost := fmt.Sprintf("%s%d", prefixHost, lastIp+int(ip))
guessTarget := fmt.Sprintf("%s:%d", guessHost, port)

fmt.Printf("Guessing %s\n", guessTarget)
if guessTarget != address && IsFoundHost(guessHost, port) {
neighbors = append(neighbors, guessTarget)
}
Expand All @@ -51,12 +55,12 @@ func GetHost() string {
hostname, err := os.Hostname()
if err != nil {
// TODO: For production, default should be first nodes IP address
return "miner_1" // Default to "miner_1" if hostname retrieval fails
return "miner-1" // Default to "miner_1" if hostname retrieval fails
}

address, err := net.LookupHost(hostname)
if err != nil {
return "miner_1" // Default to "miner_1" if host lookup fails
return "miner-1" // Default to "miner_1" if host lookup fails
}

ip := address[0] // Assuming only the first IP address is needed
Expand All @@ -66,8 +70,8 @@ func GetHost() string {
// Convert the last digit to an integer
ipNum, err := strconv.Atoi(lastDigit)
if err != nil || ipNum < 1 || ipNum > 3 {
return "miner_1" // Default to "miner_1" if the last digit is not a valid number
return "miner-1" // Default to "miner-1" if the last digit is not a valid number
}

return fmt.Sprintf("miner_%d", ipNum)
return fmt.Sprintf("miner-%d", ipNum)
}

0 comments on commit 09f2c58

Please sign in to comment.