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 Jul 31, 2023
2 parents 97446d4 + 5d100d8 commit 09d32b2
Show file tree
Hide file tree
Showing 7 changed files with 121 additions and 151 deletions.
250 changes: 110 additions & 140 deletions cmd/blockchain_server/handlers/transactions.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package handlers

import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
Expand All @@ -11,170 +10,141 @@ import (
"github.com/elarsaks/Go-blockchain/pkg/utils"
)

// TODO: Divide this function into 4 different functions
func (h *BlockchainServerHandler) HandleGetTransaction(w http.ResponseWriter, req *http.Request) {
w.Header().Add("Content-Type", "application/json")

// Transactions is a handler function that allows for getting, creating, updating and deleting transactions
func (h *BlockchainServerHandler) Transactions(w http.ResponseWriter, req *http.Request) {
// Switching on the HTTP method
switch req.Method {
bc := h.server.GetBlockchain()

// In case of a GET request, return the current transaction pool
case http.MethodGet:
// Setting the Content-Type of the response to application/json
w.Header().Add("Content-Type", "application/json")
transactions := bc.TransactionPool()

// Getting the blockchain from the server
bc := h.server.GetBlockchain()
m, _ := json.Marshal(struct {
Transactions []*block.Transaction `json:"transactions"`
Length int `json:"length"`
}{
Transactions: transactions,
Length: len(transactions),
})

// Getting the transaction pool
transactions := bc.TransactionPool()
io.WriteString(w, string(m[:]))
}

// Serializing the transaction pool and its length into a JSON object
m, _ := json.Marshal(struct {
Transactions []*block.Transaction `json:"transactions"`
Length int `json:"length"`
}{
Transactions: transactions,
Length: len(transactions),
})
func (h *BlockchainServerHandler) HandlePostTransaction(w http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(req.Body)
var t block.TransactionRequest
err := decoder.Decode(&t)

// Writing the serialized JSON object to the response
io.WriteString(w, string(m[:]))
if err != nil {
log.Printf("ERROR: %v", err)
io.WriteString(w, string(utils.JsonStatus("fail")))
return
}

// In case of a POST request, create a new transaction
case http.MethodPost:
// Decoding the body of the request into a TransactionRequest object
decoder := json.NewDecoder(req.Body)
var t block.TransactionRequest
err := decoder.Decode(&t)

// If there was an error decoding the request, log the error and send a fail response
if err != nil {
log.Printf("ERROR: %v", err)
io.WriteString(w, string(utils.JsonStatus("fail")))
return
}
if !t.Validate() {
log.Println("ERROR: missing field(s)")
io.WriteString(w, string(utils.JsonStatus("fail")))
return
}

// Validate the transaction request, send a fail response if validation fails
if !t.Validate() {
log.Println("ERROR: missing field(s)")
io.WriteString(w, string(utils.JsonStatus("fail")))
return
}
publicKey := utils.PublicKeyFromString(*t.SenderPublicKey)
signature := utils.SignatureFromString(*t.Signature)

// Convert the sender's public key and signature from strings to their appropriate types
publicKey := utils.PublicKeyFromString(*t.SenderPublicKey)
signature := utils.SignatureFromString(*t.Signature)

// Getting the blockchain from the server
bc := h.server.GetBlockchain()

// Attempting to create a new transaction
isCreated, err := bc.CreateTransaction(*t.SenderBlockchainAddress,
*t.RecipientBlockchainAddress, *t.Message, *t.Value, publicKey, signature)

// Setting the Content-Type of the response to application/json
w.Header().Add("Content-Type", "application/json")

var m []byte
if err != nil { // If there is an error during the transaction creation

w.WriteHeader(http.StatusBadRequest)
// Create an anonymous struct to hold the status and the error message
errMsg := struct {
Status string `json:"status"`
Message string `json:"message"`
}{
Status: "fail",
Message: err.Error(),
}

// Marshal the struct into a JSON string
m, _ = json.Marshal(errMsg)
} else if !isCreated { // If the transaction was not created successfully
fmt.Println(" If the transaction was not created successfully")

w.WriteHeader(http.StatusBadRequest)
m = utils.JsonStatus("fail")
} else { // If the transaction was created successfully
w.WriteHeader(http.StatusCreated)
m = utils.JsonStatus("success")
}
bc := h.server.GetBlockchain()

// Write the status message to the response
io.WriteString(w, string(m))
isCreated, err := bc.CreateTransaction(*t.SenderBlockchainAddress,
*t.RecipientBlockchainAddress, *t.Message, *t.Value, publicKey, signature)

// In case of a PUT request, update a transaction
case http.MethodPut:
// Decoding the body of the request into a TransactionRequest object
decoder := json.NewDecoder(req.Body)
var t block.TransactionRequest
err := decoder.Decode(&t)

// If there was an error decoding the request, log the error and send a fail response
if err != nil {
log.Printf("ERROR: %v", err)
io.WriteString(w, string(utils.JsonStatus("fail")))
return
}
w.Header().Add("Content-Type", "application/json")

// Validate the transaction request, send a fail response if validation fails
if !t.Validate() {
log.Println("ERROR: missing field(s)")
io.WriteString(w, string(utils.JsonStatus("fail")))
return
var m []byte
if err != nil {
w.WriteHeader(http.StatusBadRequest)
errMsg := struct {
Status string `json:"status"`
Message string `json:"message"`
}{
Status: "fail",
Message: err.Error(),
}

// Convert the sender's public key and signature from strings to their appropriate types
publicKey := utils.PublicKeyFromString(*t.SenderPublicKey)
signature := utils.SignatureFromString(*t.Signature)
m, _ = json.Marshal(errMsg)
} else if !isCreated {
w.WriteHeader(http.StatusBadRequest)
m = utils.JsonStatus("fail")
} else {
w.WriteHeader(http.StatusCreated)
m = utils.JsonStatus("success")
}

// Getting the blockchain from the server
bc := h.server.GetBlockchain()
io.WriteString(w, string(m))
}

// Updating a transaction and getting whether the transaction was updated successfully
func (h *BlockchainServerHandler) HandlePutTransaction(w http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(req.Body)
var t block.TransactionRequest
err := decoder.Decode(&t)

isUpdated, err := bc.AddTransaction(*t.SenderBlockchainAddress,
*t.RecipientBlockchainAddress,
*t.Message,
*t.Value,
publicKey,
signature)
if err != nil {
log.Printf("ERROR: %v", err)
io.WriteString(w, string(utils.JsonStatus("fail")))
return
}

if err != nil {
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{"status": "fail", "error": err.Error()})
} else {
json.NewEncoder(w).Encode(map[string]string{"status": "success"})
}
if !t.Validate() {
log.Println("ERROR: missing field(s)")
io.WriteString(w, string(utils.JsonStatus("fail")))
return
}

// Setting the Content-Type of the response to application/json
w.Header().Add("Content-Type", "application/json")
publicKey := utils.PublicKeyFromString(*t.SenderPublicKey)
signature := utils.SignatureFromString(*t.Signature)

// If the transaction was not updated successfully, send a fail status message
var m []byte
if !isUpdated {
w.WriteHeader(http.StatusBadRequest)
m = utils.JsonStatus("fail")
} else { // If the transaction was updated successfully, send a success status message
m = utils.JsonStatus("success")
}
bc := h.server.GetBlockchain()

// Write the status message to the response
io.WriteString(w, string(m))
isUpdated, err := bc.AddTransaction(*t.SenderBlockchainAddress,
*t.RecipientBlockchainAddress,
*t.Message,
*t.Value,
publicKey,
signature)

// In case of a DELETE request, clear the transaction pool
case http.MethodDelete:
// Getting the blockchain from the server
bc := h.server.GetBlockchain()
if err != nil {
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{"status": "fail", "error": err.Error()})
} else {
json.NewEncoder(w).Encode(map[string]string{"status": "success"})
}

// Clearing the transaction pool
bc.ClearTransactionPool()
w.Header().Add("Content-Type", "application/json")

var m []byte
if !isUpdated {
w.WriteHeader(http.StatusBadRequest)
m = utils.JsonStatus("fail")
} else {
m = utils.JsonStatus("success")
}

io.WriteString(w, string(m))
}

// Send a success status message
io.WriteString(w, string(utils.JsonStatus("success")))
func (h *BlockchainServerHandler) HandleDeleteTransaction(w http.ResponseWriter, req *http.Request) {
bc := h.server.GetBlockchain()

// In case of an unsupported HTTP method, log an error and send a 400 response
bc.ClearTransactionPool()

io.WriteString(w, string(utils.JsonStatus("success")))
}

func (h *BlockchainServerHandler) Transactions(w http.ResponseWriter, req *http.Request) {
switch req.Method {
case http.MethodGet:
h.HandleGetTransaction(w, req)
case http.MethodPost:
h.HandlePostTransaction(w, req)
case http.MethodPut:
h.HandlePutTransaction(w, req)
case http.MethodDelete:
h.HandleDeleteTransaction(w, req)
default:
log.Println("ERROR: Invalid HTTP Method")
w.WriteHeader(http.StatusBadRequest)
Expand Down
3 changes: 3 additions & 0 deletions cmd/react_dashboard/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ COPY package*.json ./
# Install dependencies
RUN npm install

# Create a group and user
#COPY --chown=node:node . .

# Copy the keys directory
COPY keys ./keys

Expand Down
6 changes: 3 additions & 3 deletions cmd/react_dashboard/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

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.
4 changes: 2 additions & 2 deletions cmd/react_dashboard/public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@
<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="https://saks.digital/wp-content/uploads/2023/07/some.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="http://yourdomain.com/yourpage.html" />
<meta property="og:url" content="https://elarsaks.github.io/Go-blockchain/" />
<meta property="og:type" content="website" />
<meta name=" viewport" content="width=device-width, initial-scale=1.0">
<meta name="google-site-verification" content="JF15ZtPM1uHo3jSkwn0cSU_Eo61F9sqekl5cUo3x85A" />
Expand Down
4 changes: 2 additions & 2 deletions cmd/react_dashboard/src/components/layout/Cube.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ const Cube: React.FC = () => {

// Create face material
const faceMaterial = new MeshBasicMaterial({
color: "#000000",
opacity: 0.3,
color: "#00008B",
opacity: 0.2,
transparent: true,
});
const cubeMesh = new Mesh(geometry, faceMaterial);
Expand Down
5 changes: 1 addition & 4 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ services:
- REACT_APP_GATEWAY_API_URL=http://localhost:${WALLET_SERVER_PORT}
volumes:
- ./cmd/react_dashboard:/app
- node_modules:/app/node_modules
- ./cmd/react_dashboard/node_modules:/app/node_modules

wallet-server:
container_name: wallet-server
Expand Down Expand Up @@ -68,6 +68,3 @@ services:
volumes:
- .:/app
restart: unless-stopped

volumes:
node_modules:

0 comments on commit 09d32b2

Please sign in to comment.