-
Notifications
You must be signed in to change notification settings - Fork 5
/
client.go
285 lines (239 loc) · 6.24 KB
/
client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
package ozcoin
import (
"log"
)
type ClientType uint8
const (
BLOCKCHAIN_CLIENT ClientType = iota
SVP_CLIENT
)
var SIGNAL = struct{}{}
/*
* Stores full copies of every block and txn pool.
*/
func NewBlockchain(clientAddress, walletAddress, password string) *Client {
return newClient(BLOCKCHAIN_CLIENT, clientAddress, walletAddress, password, false)
}
/*
* Only stores block headers and preimages.
*/
func NewSPV(clientAddress, walletAddress, password string) *Client {
return newClient(SVP_CLIENT, clientAddress, walletAddress, password, true)
}
/*
* Client
*
* Provides access to database operations and facilitates the consensus
* mechanisms.
*/
type Client struct {
Type ClientType
LastHeader BlockHeader
UpdateWallet bool
Address string
HeaderDBPath string
SideHeaderDBPath string
OrphanHeaderDBPath string
BlockDBPath string
SideBlockDBPath string
OrphanBlockDBPath string
MapDBPath string
UTxnDBPath string
PImgDBPath string
PeerDBPath string
TxnPoolDBPath string
Sources []string
BlockHashChan chan HashMsg
TxnHashChan chan HashMsg
BlockChan chan Block
TxnChan chan Txn
dbm *DBManager
Wallet *WalletClient
}
/*
* Builds a new client and starts the gossip rpc server.
*/
func newClient(t ClientType, clientAddress, walletAddress, password string, updateWallet bool) *Client {
client := &Client{
Type: t,
UpdateWallet: updateWallet,
HeaderDBPath: "db/header.db",
SideHeaderDBPath: "db/side-header.db",
OrphanHeaderDBPath: "db/orphan-header.db",
BlockDBPath: "db/block.db",
SideBlockDBPath: "db/side-block.db",
OrphanBlockDBPath: "db/orphan-block.db",
MapDBPath: "db/map.db",
PImgDBPath: "db/pimg.db",
PeerDBPath: "db/peer.db",
TxnPoolDBPath: "db/txn-pool.db",
Address: clientAddress,
Sources: []string{},
BlockHashChan: make(chan HashMsg),
TxnHashChan: make(chan HashMsg),
BlockChan: make(chan Block),
TxnChan: make(chan Txn),
Wallet: &WalletClient{
Address: walletAddress,
},
}
client.dbm = client.OpenDatabases()
err := client.Serve()
if err != nil {
log.Println(err)
panic("Unable to start rpc server")
}
go client.run()
return client
}
/*
* Checks to see if hash is recorded, otherwise spawns a goroutine to
* resolve hash.
*/
func (c *Client) run() {
log.Println("Running client...")
frontier := make(map[SHA256Sum]struct{})
doneChan := make(chan SHA256Sum)
startChan := make(chan struct{})
go func() {
startChan <- SIGNAL
}()
for {
select {
case req := <-c.BlockHashChan:
// Resolve incoming block hash
// Currently resolving
if _, ok := frontier[req.Hash]; ok {
continue
}
// Filter if already recorded
err := c.FilterBlock(req)
if err == nil {
continue
}
log.Println("Resolving chain")
// Unknown hash, resolve in background
frontier[req.Hash] = SIGNAL
go c.AddOrOrphan(req, startChan, doneChan)
case req := <-c.TxnHashChan:
// Resolve incoming txn hash
// Currently resolving
if _, ok := frontier[req.Hash]; ok {
continue
}
// Filter if already recorded
err := c.FilterTxn(req)
if err == nil {
continue
}
log.Println("Resolving txn")
// Unknown hash, resolve in background
frontier[req.Hash] = SIGNAL
go c.AddToTxnPool(req, startChan, doneChan)
case block := <-c.BlockChan:
// New Block
frontier[block.Header.Hash()] = SIGNAL
go c.AdoptMinedBlock(block, startChan, doneChan)
case txn := <-c.TxnChan:
// New Txn
frontier[txn.Hash()] = SIGNAL
go c.AdoptTxn(txn, startChan, doneChan)
case hash := <-doneChan:
// Remove from frontier and signal next operation
delete(frontier, hash)
go func() { startChan <- SIGNAL }()
}
}
}
/*
* Validates and adds a txn to the txn pool.
*/
func (c *Client) AdoptTxn(txn Txn, startChan chan struct{}, doneChan chan SHA256Sum) {
_ = <-startChan
// Signal when complete
defer func() { doneChan <- txn.Hash() }()
log.Println("New txn:", string(txn.Json()))
if !ValidTxn(txn) && !ValidCoinbaseTxn(txn) {
log.Println("Invalid txn")
return
}
err := c.PutTxnPool(txn)
if err != nil {
log.Println("Failed to add txn to txn pool")
return
}
log.Println("Txn added to txn pool, broadcasting")
err = c.BcastTxn(txn.Hash())
if err != nil {
log.Println("Failed to brodcast txn")
return
}
}
/*
* Validates and extends the main chain with mined block.
*/
func (c *Client) AdoptMinedBlock(block Block, startChan chan struct{}, doneChan chan SHA256Sum) {
_ = <-startChan
// Signal when complete
defer func() { doneChan <- block.Header.Hash() }()
log.Println("New block:", string(block.Json()))
if block.Header.SeqNum != 0 && c.LastHeader.Hash() != block.Header.PrevHash {
log.Println("Mined block rejected: PrevHash incorrect or not genesis block")
return
}
if !ValidHeader(block.Header) {
log.Println("Mined block rejected: invalid header")
return
}
if !c.PrevalidBlock(block) {
log.Println("Mined block rejected: block prevalidation failed")
return
}
success, err := c.ExtendMainChain(block.Header, &block)
if err != nil {
log.Println(err)
return
}
if !success {
log.Println("Failed to extend main chain")
return
}
log.Println("Mined block accpeted, broadcasting block")
err = c.BcastBlock(block.Header.Hash())
if err != nil {
log.Println("Broadcast failed")
return
}
log.Println("Broadcast successful")
}
/*
* Returns nil if client is already aware of block.
*/
func (c *Client) FilterBlock(req HashMsg) error {
// Load header from main header database
_, err := c.GetHeader(req.Hash)
if err != nil {
// Load header from sidechain header datbase
_, err = c.GetSideHeader(req.Hash)
if err != nil {
// Load header from orphan header database
_, err = c.GetOrphanHeader(req.Hash)
}
}
return err
}
/*
* Returns nil if client is already aware of txn.
*/
func (c *Client) FilterTxn(req HashMsg) error {
// Load header from txn pool database
_, err := c.GetTxnPool(req.Hash)
if err != nil {
// Check for preimage
found := c.GetPreimage(req.Hash)
if found {
err = nil
}
}
return err
}