Skip to content

Commit 683432f

Browse files
committed
finished wallet UI
1 parent b20a02b commit 683432f

File tree

4 files changed

+136
-4
lines changed

4 files changed

+136
-4
lines changed

block/blockchain.go

+27
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,15 @@ import (
88
"goBlockchain/utils"
99
"log"
1010
"strings"
11+
"sync"
1112
"time"
1213
)
1314

1415
const (
1516
MINING_DIFFICULTY = 3
1617
MINING_SENDER = "THE BLOCKCHAIN"
1718
MINING_REWARD = 1.0
19+
MINING_TIMER_SEC = 20
1820
)
1921

2022
type Block struct {
@@ -66,6 +68,7 @@ type Blockchain struct {
6668
chain []*Block
6769
blockchainAddress string
6870
port uint16
71+
mux sync.Mutex
6972
}
7073

7174
func NewBlockchain(blockchainAddress string, port uint16) *Blockchain {
@@ -176,6 +179,13 @@ func (bc *Blockchain) ProofOfWork() int {
176179
}
177180

178181
func (bc *Blockchain) Mining() bool {
182+
bc.mux.Lock()
183+
defer bc.mux.Unlock()
184+
185+
if len(bc.transactionPool) == 0 {
186+
return false
187+
}
188+
179189
bc.AddTransaction(MINING_SENDER, bc.blockchainAddress, MINING_REWARD, nil, nil)
180190
nonce := bc.ProofOfWork()
181191
previousHash := bc.LastBlock().Hash()
@@ -184,6 +194,11 @@ func (bc *Blockchain) Mining() bool {
184194
return true
185195
}
186196

197+
func (bc *Blockchain) StartMining() {
198+
bc.Mining()
199+
_ = time.AfterFunc(time.Second*MINING_TIMER_SEC, bc.StartMining)
200+
}
201+
187202
func (bc *Blockchain) CalculateTotalAmount(blockchainAddress string) float32 {
188203
var totalAmount float32 = 0.0
189204
for _, b := range bc.chain {
@@ -244,3 +259,15 @@ func (tr *TransactionRequest) Validate() bool {
244259
}
245260
return true
246261
}
262+
263+
type AmountResponse struct {
264+
Amount float32 `json:"amount"`
265+
}
266+
267+
func (ar *AmountResponse) MarshalJSON() ([]byte, error) {
268+
return json.Marshal(struct {
269+
Amount float32 `json:"amount"`
270+
}{
271+
Amount: ar.Amount,
272+
})
273+
}

blockchain_server/blockchain_server.go

+35
Original file line numberDiff line numberDiff line change
@@ -123,9 +123,44 @@ func (bcs *BlockchainServer) Mine(w http.ResponseWriter, req *http.Request) {
123123
}
124124
}
125125

126+
func (bcs *BlockchainServer) StartMine(w http.ResponseWriter, req *http.Request) {
127+
switch req.Method {
128+
case http.MethodGet:
129+
bc := bcs.GetBlockchain()
130+
bc.StartMining()
131+
132+
m := utils.JsonStatus("success")
133+
w.Header().Add("Content-Type", "application/json")
134+
io.WriteString(w, string(m))
135+
default:
136+
log.Println("ERROR: Invalid HTTP Method")
137+
w.WriteHeader(http.StatusBadRequest)
138+
}
139+
}
140+
141+
func (bcs *BlockchainServer) Amount(w http.ResponseWriter, req *http.Request) {
142+
switch req.Method {
143+
case http.MethodGet:
144+
blockchainAddress := req.URL.Query().Get("blockchain_address")
145+
amount := bcs.GetBlockchain().CalculateTotalAmount(blockchainAddress)
146+
147+
ar := &block.AmountResponse{amount}
148+
m, _ := ar.MarshalJSON()
149+
150+
w.Header().Add("Content-Type", "application/json")
151+
io.WriteString(w, string(m[:]))
152+
153+
default:
154+
log.Printf("ERROR: Invalid HTTP Method")
155+
w.WriteHeader(http.StatusBadRequest)
156+
}
157+
}
158+
126159
func (bcs *BlockchainServer) Run() {
127160
http.HandleFunc("/", bcs.GetChain)
128161
http.HandleFunc("/transactions", bcs.Transactions)
129162
http.HandleFunc("/mine", bcs.Mine)
163+
http.HandleFunc("/mine/start", bcs.StartMine)
164+
http.HandleFunc("/amount", bcs.Amount)
130165
log.Fatal(http.ListenAndServe("0.0.0.0:"+strconv.Itoa(int(bcs.Port())), nil))
131166
}

wallet_server/templates/index.html

+24-4
Original file line numberDiff line numberDiff line change
@@ -43,10 +43,6 @@
4343
data: JSON.stringify(transaction_data),
4444
success: function (response) {
4545
console.info(response);
46-
if ($.parseJSON(response).message === 'fail') {
47-
alert("failed")
48-
return
49-
}
5046
alert('Send success');
5147
},
5248
error: function (response) {
@@ -55,6 +51,30 @@
5551
}
5652
})
5753
})
54+
55+
function reload_amount() {
56+
let data = {'blockchain_address': $('#blockchain_address').val()}
57+
$.ajax({
58+
url: '/wallet/amount',
59+
type: 'GET',
60+
data: data,
61+
success: function (response) {
62+
let amount = response['amount'];
63+
$('#wallet_amount').text(amount);
64+
console.info(amount)
65+
},
66+
error: function(error) {
67+
console.error(error)
68+
}
69+
})
70+
}
71+
72+
$('#reload_wallet').click(function(){
73+
reload_amount();
74+
});
75+
76+
// setInterval(reload_amount, 3000)
77+
5878
})
5979

6080
</script>

wallet_server/wallet_server.go

+50
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package main
33
import (
44
"bytes"
55
"encoding/json"
6+
"fmt"
67
"goBlockchain/block"
78
"goBlockchain/utils"
89
"goBlockchain/wallet"
@@ -111,9 +112,58 @@ func (ws *WalletServer) CreateTransaction(w http.ResponseWriter, req *http.Reque
111112
}
112113
}
113114

115+
func (ws *WalletServer) WalletAmount(w http.ResponseWriter, req *http.Request) {
116+
switch req.Method {
117+
case http.MethodGet:
118+
blockchainAddress := req.URL.Query().Get("blockchain_address")
119+
endpoint := fmt.Sprintf("%s/amount", ws.Gateway())
120+
121+
client := &http.Client{}
122+
bcsReq, _ := http.NewRequest("GET", endpoint, nil)
123+
q := bcsReq.URL.Query()
124+
q.Add("blockchain_address", blockchainAddress)
125+
bcsReq.URL.RawQuery = q.Encode()
126+
127+
bcsResp, err := client.Do(bcsReq)
128+
if err != nil {
129+
log.Printf("ERROR: %v", err)
130+
io.WriteString(w, string(utils.JsonStatus("fail")))
131+
return
132+
}
133+
134+
w.Header().Add("Content-Type", "application/json")
135+
if bcsResp.StatusCode == 200 {
136+
decoder := json.NewDecoder(bcsResp.Body)
137+
var bar block.AmountResponse
138+
err := decoder.Decode(&bar)
139+
if err != nil {
140+
log.Printf("ERROR: %v", err)
141+
io.WriteString(w, string(utils.JsonStatus("fail")))
142+
return
143+
}
144+
145+
m, _ := json.Marshal(struct {
146+
Message string `json:"message"`
147+
Amount float32 `json:"amount"`
148+
}{
149+
Message: "success",
150+
Amount: bar.Amount,
151+
})
152+
io.WriteString(w, string(m[:]))
153+
} else {
154+
io.WriteString(w, string(utils.JsonStatus("fail")))
155+
}
156+
157+
default:
158+
log.Printf("ERROR: Invalid HTTP Method")
159+
w.WriteHeader(http.StatusBadRequest)
160+
}
161+
}
162+
114163
func (ws *WalletServer) Run() {
115164
http.HandleFunc("/", ws.Index)
116165
http.HandleFunc("/wallet", ws.Wallet)
166+
http.HandleFunc("/wallet/amount", ws.WalletAmount)
117167
http.HandleFunc("/transaction", ws.CreateTransaction)
118168
log.Fatal(http.ListenAndServe("0.0.0.0:"+strconv.Itoa(int(ws.Port())), nil))
119169
}

0 commit comments

Comments
 (0)