Skip to content

Commit

Permalink
added automated mining trigger
Browse files Browse the repository at this point in the history
  • Loading branch information
jagottsicher committed Feb 10, 2024
1 parent 5e9c85d commit ad89a60
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
16 changes: 16 additions & 0 deletions blockchain/blockchain.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import (
"fmt"
"log"
"strings"
"sync"
"time"

"github.com/jagottsicher/myGoBlockchain/utils"
)
Expand All @@ -15,13 +17,15 @@ const (
MINING_DIFFICULTY = 3
MINING_SENDER = "BLOCKCHAIN REWARD SYSTEM (e.g. minting & fees)"
MINING_REWARD = 1.0
MINING_TIMER_SEC = 20
)

type Blockchain struct {
transactionPool []*Transaction
chain []*Block
blockchainAddress string
port uint16
mux sync.Mutex
}

func NewBlockchain(blockchainAddress string, port uint16) *Blockchain {
Expand Down Expand Up @@ -129,6 +133,13 @@ func (bc *Blockchain) LastBlock() *Block {
}

func (bc *Blockchain) Mining() bool {
bc.mux.Lock()
defer bc.mux.Unlock()

if len(bc.TransactionPool()) == 0 {
return false
}

bc.AddTransaction(MINING_SENDER, bc.blockchainAddress, MINING_REWARD, nil, nil)
nonce := bc.ProofOfWork()
previousHash := bc.LastBlock().Hash()
Expand All @@ -137,6 +148,11 @@ func (bc *Blockchain) Mining() bool {
return true
}

func (bc *Blockchain) StartMining() {
bc.Mining()
_ = time.AfterFunc(time.Second*MINING_TIMER_SEC, bc.StartMining)
}

func (bc *Blockchain) CalculateTotalAmount(blockchainAddress string) float32 {
var totalAmount float32 = 0
for _, b := range bc.chain {
Expand Down
16 changes: 16 additions & 0 deletions blockchain_node/blockchain_node.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,10 +126,26 @@ func (bcn *BlockchainNode) Mine(w http.ResponseWriter, r *http.Request) {
}
}

func (bcn *BlockchainNode) StartMine(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
bc := bcn.GetBlockchain()
bc.StartMining()

m := utils.JsonStatus("success")
w.Header().Add("Content-Type", "application/json")
io.WriteString(w, string(m))
default:
log.Println("ERROR: Invalid HTTP method")
w.WriteHeader(http.StatusBadRequest)
}
}

func (bcn *BlockchainNode) Run() {
http.HandleFunc("/", bcn.GetChain)
http.HandleFunc("/transactions", bcn.Transactions)
http.HandleFunc("/mine", bcn.Mine)
http.HandleFunc("/mine/start", bcn.StartMine)

log.Fatal(http.ListenAndServe("0.0.0.0:"+strconv.Itoa(int(bcn.Port())), nil))
}

0 comments on commit ad89a60

Please sign in to comment.