-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathguts.go
450 lines (325 loc) · 12.8 KB
/
guts.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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
// jeffCoin 1. BLOCKCHAIN guts.go
package blockchain
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"sort"
"strconv"
"sync"
"time"
log "github.com/sirupsen/logrus"
)
var mutex = &sync.Mutex{}
func checkErr(err error) {
if err != nil {
fmt.Printf("Error is %+v\n", err)
log.Fatal("ERROR:", err)
}
}
// BLOCKCHAIN ************************************************************************************************************
// getBlockchain - Gets the blockchain
func getBlockchain() blockchainSlice {
s := "START getBlockchain() - Gets the blockchain"
log.Debug("BLOCKCHAIN: GUTS " + s)
s = "END getBlockchain() - Gets the blockchain"
log.Debug("BLOCKCHAIN: GUTS " + s)
return blockchain
}
// loadBlockchain - Loads the entire blockchain
func loadBlockchain(message string) {
s := "START loadBlockchain() - Loads the entire blockchain"
log.Debug("BLOCKCHAIN: GUTS " + s)
// LOAD
json.Unmarshal([]byte(message), &blockchain)
s = "END loadBlockchain() - Loads the entire blockchain"
log.Debug("BLOCKCHAIN: GUTS " + s)
}
// replaceBlockchain - Replaces blockchain with the longer one
func replaceBlockchain(newBlock blockchainSlice) {
s := "START replaceChain() - Replaces blockchain with the longer one"
log.Debug("BLOCKCHAIN: GUTS " + s)
if len(newBlock) > len(blockchain) {
s = "New block added to chain"
log.Info("BLOCKCHAIN: GUTS " + s)
blockchain = newBlock
} else {
s = "New Block NOT added to chain"
log.Info("BLOCKCHAIN: GUTS " + s)
}
s = "END replaceChain() - Replaces blockchain with the longer one"
log.Debug("BLOCKCHAIN: GUTS " + s)
}
// BLOCK *****************************************************************************************************************
// getBlock - Gets a block in the blockchain
func getBlock(blockID string) blockStruct {
s := "START getBlock() - Gets a block in the blockchain"
log.Debug("BLOCKCHAIN: GUTS " + s)
var blockItem blockStruct
blockIDint, _ := strconv.ParseInt(blockID, 10, 64)
blockItem = blockchain[blockIDint]
s = "END getBlock() - Gets a block in the blockchain"
log.Debug("BLOCKCHAIN: GUTS " + s)
return blockItem
}
// calculateBlockHash - Calculates SHA256 hash on a block
func calculateBlockHash(block blockStruct) string {
s := "START calculateBlockHash() - Calculates SHA256 hash on a block"
log.Debug("BLOCKCHAIN: GUTS " + s)
// GET ALL THE TRANSACTIONS
transactionBytes := []byte{}
for _, transaction := range block.Transactions {
transactionBytes, _ = json.Marshal(transaction)
}
// HASH blockID, timestamp, transactions, prevhash, difficulty, nonce
hashMe := strconv.FormatInt(block.BlockID, 10) + block.Timestamp + string(transactionBytes) + block.PrevHash + strconv.Itoa(block.Difficulty) + block.Nonce
hashedByte := sha256.Sum256([]byte(hashMe))
hashed := hex.EncodeToString(hashedByte[:])
s = "Calculated block Hash: " + hashed
log.Info("BLOCKCHAIN: GUTS " + s)
s = "END calculateBlockHash() - Calculates SHA256 hash on a block"
log.Debug("BLOCKCHAIN: GUTS " + s)
return hashed
}
// isBlockValid - Checks if block is valid
func isBlockValid(checkBlock, oldBlock blockStruct) bool {
s := "START isBlockValid() - Checks if block is valid"
log.Debug("BLOCKCHAIN: GUTS " + s)
// Check index
if oldBlock.BlockID+1 != checkBlock.BlockID {
return false
}
// Compare the hash matches
if oldBlock.Hash != checkBlock.PrevHash {
return false
}
// Recalculate Hash to check
if calculateBlockHash(checkBlock) != checkBlock.Hash {
return false
}
s = "END isBlockValid() - Checks if block is valid"
log.Debug("BLOCKCHAIN: GUTS " + s)
return true
}
// LOCKED BLOCK **********************************************************************************************************
// getLockedBlock - Gets the lockedBlock
func getLockedBlock() blockStruct {
s := "START getLockedBlock() - Gets the lockedBlock"
log.Debug("BLOCKCHAIN: GUTS " + s)
s = "END getLockedBlock() - Gets the lockedBlock"
log.Debug("BLOCKCHAIN: GUTS " + s)
return lockedBlock
}
// appendLockedBlock - Appends the lockedBlock to the blockchain
func appendLockedBlock() {
s := "START appendLockedBlock() - Appends the lockedBlock to the blockchain"
log.Debug("BLOCKCHAIN: GUTS " + s)
mutex.Lock()
blockchain = append(blockchain, lockedBlock)
mutex.Unlock()
s = "END appendLockedBlock() - Appends the lockedBlock to the blockchain"
log.Debug("BLOCKCHAIN: GUTS " + s)
}
// PENDING BLOCK *********************************************************************************************************
// getPendingBlock - Gets the pendingBlock
func getPendingBlock() blockStruct {
s := "START getPendingBlock() - Gets the pendingBlock"
log.Debug("BLOCKCHAIN: GUTS " + s)
s = "END getPendingBlock() - Gets the pendingBlock"
log.Debug("BLOCKCHAIN: GUTS " + s)
return pendingBlock
}
// loadPendingBlock - Loads the pendingBlock
func loadPendingBlock(blockDataString string) {
s := "START loadPendingBlock() - Loads the pendingBlock"
log.Debug("BLOCKCHAIN: GUTS " + s)
// LOAD THE PENDING BLOCK - Place block data in pendingBlock
blockDataByte := []byte(blockDataString)
err := json.Unmarshal(blockDataByte, &pendingBlock)
checkErr(err)
// TIMESTAMP BLOCK
t := time.Now()
pendingBlock.Timestamp = t.String()
s = "END loadPendingBlock() - Loads the pendingBlock"
log.Debug("BLOCKCHAIN: GUTS " + s)
}
// resetPendingBlock - Resets the pendingBlock
func resetPendingBlock() {
s := "START resetPendingBlock() - Resets the pendingBlock"
log.Debug("BLOCKCHAIN: GUTS " + s)
var transactionSlice []transactionStruct
var transaction transactionStruct
t := time.Now()
// INCREMENT BlockID
pendingBlock.BlockID = pendingBlock.BlockID + 1
// TIMESTAMP THE PENDING BLOCK
pendingBlock.Timestamp = t.String()
// TRANSACTIONS
// INCREMENT TxID (From last one)
transaction.TxID = pendingBlock.Transactions[len(pendingBlock.Transactions)-1].TxID + 1
transactionSlice = append(transactionSlice, transaction)
// HASH
pendingBlock.Hash = ""
// PREVIOUS HASH FROM BLOCKCHAIN
// I know, I incremented it above
theBlock := getBlock(string(pendingBlock.BlockID - 1))
pendingBlock.PrevHash = theBlock.Hash
// DIFFICULTY
pendingBlock.Difficulty = pendingBlock.Difficulty
// NONCE
pendingBlock.Nonce = ""
// LOAD THE BLOCK
pendingBlock.Transactions = transactionSlice
s = "END resetPendingBlock() - Resets the pendingBlock"
log.Debug("BLOCKCHAIN: GUTS " + s)
}
// addTransactionToPendingBlock - Adds a transaction to the pendingBlock and makes change
func (trms txRequestMessageSignedStruct) addTransactionToPendingBlock(unspentOutputSlice []unspentOutputStruct, change int64) {
s := "START addTransactionToPendingBlock() - Adds a transaction to the pendingBlock and makes change"
log.Debug("BLOCKCHAIN: GUTS " + s)
// Check if first transaction in pendingBlock
first := false
if pendingBlock.Transactions[0].Inputs == nil {
first = true
}
//-------------------------------------------------------
// STEP 1 - BUILD INPUT STRUCT FOR EACH UNSPENT OUTPUT
//-------------------------------------------------------
s = "STEP 1 - BUILD INPUT STRUCT FOR EACH UNSPENT OUTPUT"
log.Info("BLOCKCHAIN: GUTS " + s)
var inputsTemp = inputsStruct{}
var inputsSlice []inputsStruct
// Using the following unspent outputs
for _, unspentOutput := range unspentOutputSlice {
inputsTemp.RefTxID = unspentOutput.TxID
inputsTemp.InPubKey = trms.TxRequestMessage.SourceAddress
inputsTemp.Signature = trms.Signature
// Place in slice
inputsSlice = append(inputsSlice, inputsTemp)
}
//-------------------------------------------------------
// STEP 2 - BUILD OUTPUT STRUCT
//-------------------------------------------------------
s = "STEP 2 - BUILD OUTPUT STRUCT"
log.Info("BLOCKCHAIN: GUTS " + s)
var outputsTemp = outputsStruct{}
var outputsSlice []outputsStruct
// Using the following destinations
for _, destination := range trms.TxRequestMessage.Destinations {
outputsTemp.OutPubKey = destination.DestinationAddress
outputsTemp.Value = destination.Value
// Place in slice
outputsSlice = append(outputsSlice, outputsTemp)
}
// PROVIDE CHANGE if > 0
if change > 0 {
outputsTemp.OutPubKey = trms.TxRequestMessage.SourceAddress
outputsTemp.Value = change
// Place in slice
outputsSlice = append(outputsSlice, outputsTemp)
}
//-------------------------------------------------------
// STEP 3 - BUILD THE TRANSACTION
//-------------------------------------------------------
s = "STEP 3 - BUILD THE TRANSACTION"
log.Info("BLOCKCHAIN: GUTS " + s)
var transactionTemp = transactionStruct{}
// Check if first transaction
if first {
transactionTemp.TxID = pendingBlock.Transactions[0].TxID
} else {
transactionTemp.TxID = pendingBlock.Transactions[len(pendingBlock.Transactions)-1].TxID + 1
}
transactionTemp.Inputs = inputsSlice
transactionTemp.Outputs = outputsSlice
s = "The transactionTemp is (-loglevel trace to display)"
log.Info("BLOCKCHAIN: GUTS " + s)
js, _ := json.MarshalIndent(transactionTemp, "", " ")
log.Trace("\n\n" + string(js) + "\n\n")
//-------------------------------------------------------
// STEP 4 - PLACE transactionStruct IN transactionSlice
//-------------------------------------------------------
s = "STEP 4 - PLACE transactionStruct IN transactionSlice"
log.Info("BLOCKCHAIN: GUTS " + s)
var transactionSlice []transactionStruct
// Check if first transaction
if first {
transactionSlice = append(transactionSlice, transactionTemp)
} else {
transactionSlice = append(pendingBlock.Transactions, transactionTemp)
}
//-------------------------------------------------------
// STEP 5 - LOAD THE PENDING BLOCK WITH TRANSACTION
//-------------------------------------------------------
s = "STEP 5 - LOAD THE PENDING BLOCK WITH TRANSACTION"
log.Info("BLOCKCHAIN: GUTS " + s)
pendingBlock.Transactions = transactionSlice
s = "END addTransactionToPendingBlock() - Adds a transaction to the pendingBlock and makes change"
log.Debug("BLOCKCHAIN: GUTS " + s)
}
// lockPendingBlock - Moves the pendingBlock to the lockedBlock
func lockPendingBlock(difficulty int) {
s := "START lockPendingBlock() - Moves the pendingBlock to the lockedBlock"
log.Debug("BLOCKCHAIN: GUTS " + s)
pendingBlock.Hash = calculateBlockHash(pendingBlock)
pendingBlock.Difficulty = difficulty
lockedBlock = pendingBlock
s = "END lockPendingBlock() - Moves the pendingBlock to the lockedBlock"
log.Debug("BLOCKCHAIN: GUTS " + s)
}
// JEFFCOINS *************************************************************************************************************
// getAddressBalance - Gets the jeffCoin Address balance
// Returns entire list of the TxID of output unspent transactions
func getAddressBalance(jeffCoinAddress string) (int64, []unspentOutputStruct) {
s := "START getAddressBalance() - Gets the jeffCoin Address balance"
log.Debug("BLOCKCHAIN: GUTS " + s)
unspentOutputMap := make(map[int64]int64)
var unspentOutput unspentOutputStruct
unspentOutputSlice := []unspentOutputStruct{}
// GET UNSPENT OUTPUT TRANSACTIONS - Make unspentOutputSlice
s = "GET UNSPENT OUTPUT TRANSACTIONS - Make unspentOutputSlice"
log.Info("BLOCKCHAIN: GUTS " + s)
// LETS ITERATE OVER ALL TRANSACTIONS IN BLOCK CHAIN
for _, blocks := range blockchain {
for _, transaction := range blocks.Transactions {
// ITERATE OVER INPUTS - find inputs with address
for _, input := range transaction.Inputs {
if jeffCoinAddress == input.InPubKey {
// DID AN OUTPUT USE THIS? If so, delete from map.
refTxID := input.RefTxID
if unspentOutputMap[refTxID] != 0 {
delete(unspentOutputMap, refTxID)
}
}
}
// ITERATE OVER OUTPUTS - find outputs with address
for _, output := range transaction.Outputs {
if jeffCoinAddress == output.OutPubKey {
// Place in map
unspentOutputMap[transaction.TxID] = output.Value
}
}
}
}
// PUT MAP unspentOutputMap IN SLICE unspentOutputSlice
for k, v := range unspentOutputMap {
unspentOutput = unspentOutputStruct{k, v}
unspentOutputSlice = append(unspentOutputSlice, unspentOutput)
}
// SORT SLICE FROM TxID (LOW TO HIGH)
sort.Slice(unspentOutputSlice, func(i, j int) bool {
return unspentOutputSlice[i].TxID < unspentOutputSlice[j].TxID
})
// STEP 2.2 - GET BALANCE from unspentOutputSlice
s = "GET BALANCE from unspentOutputSlice"
log.Info("BLOCKCHAIN: GUTS " + s)
var balance int64
balance = 0
for _, unspentOutput := range unspentOutputSlice {
balance = balance + unspentOutput.Value
}
s = "END getAddressBalance() - Gets the jeffCoin Address balance"
log.Debug("BLOCKCHAIN: GUTS " + s)
return balance, unspentOutputSlice
}