This repository has been archived by the owner on Jan 27, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
blockchain.go
669 lines (532 loc) · 13.3 KB
/
blockchain.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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
package main
import (
"bytes"
"crypto/ecdsa"
"encoding/hex"
"errors"
"fmt"
"github.com/boltdb/bolt"
"log"
"os"
"strconv"
"strings"
)
const dbFile = "blockchain_%s.db"
const transactionsBucket = "blocks"
const productsBucket = "products"
const organisationBucket = "organisations"
const genesisCoinbaseData = "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks"
// Blockchain implements interactions with a DB
type Blockchain struct {
tip1 []byte
tip2 []byte
tip3 []byte
db *bolt.DB
}
// CreateBlockchain creates a new blockchain DB
func CreateBlockchain(name, pubKey, gstin, prefix string, nodeID string) {
dbFile := fmt.Sprintf(dbFile, nodeID)
if dbExists(nodeID) {
fmt.Println("Blockchain already exists.")
os.Exit(1)
}
bc := NewBlockchain(nodeID)
var tip1 []byte
var tip2 []byte
var tip3 []byte
pub, _ := hex.DecodeString(pubKey)
org := &Organisation{nil, []byte(name), []byte(strings.ToUpper(gstin)), []byte(prefix), []byte("Admin"), nil, pub, nil}
org.ID = org.Hash()
userGenesis := NewBlock(nil, nil, org, nil, bc.GetBestHeight())
db, err := bolt.Open(dbFile, 0600, nil)
if err != nil {
log.Panic(err)
}
err = db.Update(func(tx *bolt.Tx) error {
_, err = tx.CreateBucket([]byte(utxoBucket))
if err != nil {
log.Panic(err)
}
b, err := tx.CreateBucket([]byte(transactionsBucket))
if err != nil {
log.Panic(err)
}
err = b.Put([]byte("l"), nil)
if err != nil {
log.Panic(err)
}
b, err = tx.CreateBucket([]byte(productsBucket))
if err != nil {
log.Panic(err)
}
err = b.Put([]byte("l"), nil)
if err != nil {
log.Panic(err)
}
b, err = tx.CreateBucket([]byte(organisationBucket))
if err != nil {
log.Panic(err)
}
err = b.Put(userGenesis.Hash, userGenesis.Serialize())
if err != nil {
log.Panic(err)
}
err = b.Put([]byte("l"), userGenesis.Hash)
if err != nil {
log.Panic(err)
}
tip3 = userGenesis.Hash
tip1 = nil
tip2 = nil
return nil
})
if err != nil {
log.Panic(err)
}
}
// Reset removes all blockchain data
func (bc *Blockchain) Reset() {
}
// AddBlock saves the block into the blockchain
func (bc *Blockchain) AddBlock(block *Block) {
err := bc.db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(transactionsBucket))
blockInDb := b.Get(block.Hash)
if blockInDb != nil {
return nil
}
blockData := block.Serialize()
err := b.Put(block.Hash, blockData)
if err != nil {
log.Panic(err)
}
lastHash := b.Get([]byte("l"))
lastBlockData := b.Get(lastHash)
lastBlock := DeserializeBlock(lastBlockData)
if block.Height > lastBlock.Height {
err = b.Put([]byte("l"), block.Hash)
if err != nil {
log.Panic(err)
}
bc.tip1 = block.Hash
}
return nil
})
if err != nil {
log.Panic(err)
}
}
// NewBlockchain creates a new Blockchain with genesis Block
func NewBlockchain(nodeID string) *Blockchain {
dbFile := fmt.Sprintf(dbFile, nodeID)
if dbExists(nodeID) == false {
fmt.Println("No existing blockchain found. Create one first.")
os.Exit(1)
}
var tip1 []byte
var tip2 []byte
var tip3 []byte
db, err := bolt.Open(dbFile, 0600, nil)
if err != nil {
log.Panic(err)
}
err = db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(transactionsBucket))
tip1 = b.Get([]byte("l"))
return nil
})
err = db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(productsBucket))
tip2 = b.Get([]byte("l"))
return nil
})
err = db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(organisationBucket))
tip3 = b.Get([]byte("l"))
return nil
})
if err != nil {
log.Panic(err)
}
bc := Blockchain{tip1, tip2, tip3, db}
return &bc
}
// FindTransaction finds a transaction by its ID
func (bc *Blockchain) FindTransaction(ID []byte) (Transaction, error) {
bci := bc.Iterator()
for {
block := bci.Next1()
for _, tx := range block.Transactions {
if bytes.Compare(tx.ID, ID) == 0 {
return *tx, nil
}
}
if len(block.PrevBlockHash) == 0 {
break
}
}
return Transaction{}, errors.New("Transaction is not found")
}
// GetBestHeight returns the height of the latest block
func (bc *Blockchain) GetBestHeight() int {
var lastBlock Block
err := bc.db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(transactionsBucket))
lastHash := b.Get([]byte("l"))
blockData := b.Get(lastHash)
lastBlock = *DeserializeBlock(blockData)
return nil
})
if err != nil {
log.Panic(err)
}
return lastBlock.Height
}
// GetBlock finds a block by its hash and returns it
func (bc *Blockchain) GetBlock(blockHash []byte) (Block, error) {
var block Block
err := bc.db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(transactionsBucket))
blockData := b.Get(blockHash)
if blockData == nil {
return errors.New("Block is not found.")
}
block = *DeserializeBlock(blockData)
return nil
})
if err != nil {
return block, err
}
return block, nil
}
// FindUTXO finds all unspent transaction outputs and returns transactions with spent outputs removed
func (bc *Blockchain) FindUTXO() map[string]TXOutputs {
UTXO := make(map[string]TXOutputs)
spentTXOs := make(map[string][]int)
bci := bc.Iterator()
if len(bc.tip1) != 0 {
for {
block := bci.Next1()
for _, tx := range block.Transactions {
txID := hex.EncodeToString(tx.ID)
Outputs:
for outIdx, out := range tx.Vout {
// Was the output spent?
if spentTXOs[txID] != nil {
for _, spentOutIdx := range spentTXOs[txID] {
if spentOutIdx == outIdx {
continue Outputs
}
}
}
outs := UTXO[txID]
outs.Outputs = append(outs.Outputs, out)
UTXO[txID] = outs
}
if tx.IsCoinbase() == false {
for _, in := range tx.Vin {
inTxID := hex.EncodeToString(in.Txid)
spentTXOs[inTxID] = append(spentTXOs[inTxID], in.Vout)
}
}
}
if len(block.PrevBlockHash) == 0 {
break
}
}
}
return UTXO
}
// Iterator returns a BlockchainIterat
func (bc *Blockchain) Iterator() *BlockchainIterator {
bci := &BlockchainIterator{bc.tip1, bc.tip2, bc.tip3, bc.db}
return bci
}
// GetBlockHashes returns a list of hashes of all the blocks in the chain
func (bc *Blockchain) GetBlockHashes(typ string) [][]byte {
var blocks [][]byte
bci := bc.Iterator()
for {
if typ == "t" {
block := bci.Next1()
} else if typ == "p" {
block := bci.Next2()
} else {
block := bci.Next3()
}
blocks = append(blocks, block.Hash)
if len(block.PrevBlockHash) == 0 {
break
}
}
return blocks
}
// MineBlock mines a new block with the provided transactions or products
func (bc *Blockchain) MineBlock(transactions []*Transaction, products []*Product, organisation *Organisation, address string) *Block {
var lastHash []byte
var lastHeight int
if transactions != nil {
for _, tx := range transactions {
if bc.VerifyTransaction(tx) != true {
log.Panic("ERROR: Invalid transaction")
}
}
err := bc.db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(transactionsBucket))
lastHash = b.Get([]byte("l"))
blockData := b.Get(lastHash)
block := DeserializeBlock(blockData)
lastHeight = block.Height
return nil
})
if err != nil {
log.Panic(err)
}
newBlock := NewBlock(transactions, nil, nil, lastHash, lastHeight+1)
err = bc.db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(transactionsBucket))
err := b.Put(newBlock.Hash, newBlock.Serialize())
if err != nil {
log.Panic(err)
}
err = b.Put([]byte("l"), newBlock.Hash)
if err != nil {
log.Panic(err)
}
bc.tip1 = newBlock.Hash
return nil
})
if err != nil {
log.Panic(err)
}
return newBlock
} else if products != nil {
for _, p := range products {
if p.Verify(Base58Decode([]byte(address))) != true {
log.Panic("ERROR: Invalid product")
}
}
err := bc.db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(productsBucket))
lastHash = b.Get([]byte("l"))
blockData := b.Get(lastHash)
block := DeserializeBlock(blockData)
lastHeight = block.Height
return nil
})
if err != nil {
log.Panic(err)
}
newBlock := NewBlock(nil, products, nil, lastHash, lastHeight+1)
err = bc.db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(productsBucket))
err := b.Put(newBlock.Hash, newBlock.Serialize())
if err != nil {
log.Panic(err)
}
err = b.Put([]byte("l"), newBlock.Hash)
if err != nil {
log.Panic(err)
}
bc.tip2 = newBlock.Hash
return nil
})
if err != nil {
log.Panic(err)
}
return newBlock
} else {
for _, p := range products {
if p.Verify(Base58Decode([]byte(address))) != true {
log.Panic("ERROR: Invalid organisation")
}
}
err := bc.db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(organisationBucket))
lastHash = b.Get([]byte("l"))
blockData := b.Get(lastHash)
block := DeserializeBlock(blockData)
lastHeight = block.Height
return nil
})
if err != nil {
log.Panic(err)
}
newBlock := NewBlock(nil, nil, organisation, lastHash, lastHeight+1)
err = bc.db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(organisationBucket))
err := b.Put(newBlock.Hash, newBlock.Serialize())
if err != nil {
log.Panic(err)
}
err = b.Put([]byte("l"), newBlock.Hash)
if err != nil {
log.Panic(err)
}
bc.tip3 = newBlock.Hash
return nil
})
if err != nil {
log.Panic(err)
}
return newBlock
}
}
// SignTransaction signs inputs of a Transaction
func (bc *Blockchain) SignTransaction(tx *Transaction, privKey ecdsa.PrivateKey) {
prevTXs := make(map[string]Transaction)
for _, vin := range tx.Vin {
prevTX, err := bc.FindTransaction(vin.Txid)
if err != nil {
log.Panic(err)
}
prevTXs[hex.EncodeToString(prevTX.ID)] = prevTX
}
tx.Sign(privKey, prevTXs)
}
// VerifyTransaction verifies transaction input signatures
func (bc *Blockchain) VerifyTransaction(tx *Transaction) bool {
if tx.IsCoinbase() {
return true
}
prevTXs := make(map[string]Transaction)
for _, vin := range tx.Vin {
prevTX, err := bc.FindTransaction(vin.Txid)
if err != nil {
log.Panic(err)
}
prevTXs[hex.EncodeToString(prevTX.ID)] = prevTX
}
return tx.Verify(prevTXs)
}
func dbExists(dbFile string) bool {
if _, err := os.Stat(dbFile); os.IsNotExist(err) {
return false
}
return true
}
// FindProductByCode finds a product by its Code
func (bc *Blockchain) FindProductByCode(address string, Code int) (Product, error) {
bci := bc.Iterator()
if len(bc.tip2) != 0 {
for {
block := bci.Next2()
for _, p := range block.Products {
if Code == p.Code && p.Verify(Base58Decode([]byte(address))) {
return *p, nil
}
}
if len(block.PrevBlockHash) == 0 {
break
}
}
}
return Product{}, errors.New("Product is not found")
}
// FindProductByCode finds a product by its Code
func (bc *Blockchain) GetNextProductCode(address string) int {
bci := bc.Iterator()
if len(bc.tip2) != 0 {
for {
block := bci.Next2()
var code int
found := false
for _, p := range block.Products {
if p.Verify(Base58Decode([]byte(address))) {
found = true
code = p.Code + 1
}
}
if found {
return code
}
if len(block.PrevBlockHash) == 0 {
break
}
}
}
return 1
}
// FindOrganisationByPublicKey finds a organisation by its pubKey
func (bc *Blockchain) FindOrganisationByPublicKey(pubKey []byte) (Organisation, error) {
bci := bc.Iterator()
for {
block := bci.Next3()
org := block.Organisation
if bytes.Compare(pubKey, org.PubKey) == 0 {
return *org, nil
}
if len(block.PrevBlockHash) == 0 {
break
}
}
return Organisation{}, errors.New("Organisation not found")
}
// GetRole gives role of organisation by public key
func (bc *Blockchain) GetRole(pubKey []byte) []byte {
bci := bc.Iterator()
for {
block := bci.Next3()
org := block.Organisation
if bytes.Compare(pubKey, org.PubKey) == 0 {
return org.Role
}
if len(block.PrevBlockHash) == 0 {
break
}
}
return nil
}
// isOrgDuplicate checks if credentials of organisation are duplicate
func (bc *Blockchain) isOrgDuplicate(gstin, prefix, pubKey []byte) bool {
bci := bc.Iterator()
for {
block := bci.Next3()
org := block.Organisation
if bytes.Compare(gstin, org.GSTIN) == 0 || bytes.Compare(pubKey, org.PubKey) == 0 || bytes.Compare(prefix, org.Prefix) == 0 {
return true
}
if len(block.PrevBlockHash) == 0 {
break
}
}
return false
}
// GenerateSGTIN gives SGTIN code by manufacturer pubKey, product code
func (bc *Blockchain) GenerateSGTIN(address string, pubKey []byte, code int) (string, error) {
bci := bc.Iterator()
_, err := bc.FindProductByCode(address, code)
if err != nil {
return "", err
}
org, err := bc.FindOrganisationByPublicKey(pubKey)
if err != nil {
return "", err
}
if len(bc.tip1) != 0 {
found := false
var serial int
for {
block := bci.Next1()
for _, tx := range block.Transactions {
if tx.IsCoinbase() {
for _, out := range tx.Vout {
codeArr := strings.Split(out.Item, ".")
i, _ := strconv.Atoi(string(codeArr[1]))
if bytes.Compare([]byte(codeArr[0]), org.Prefix) == 0 && i == code {
found = true
serial, _ = strconv.Atoi(string(codeArr[2]))
}
}
if found {
return string(org.Prefix) + "." + strconv.Itoa(code) + "." + strconv.Itoa(serial+1), nil
}
}
}
if len(block.PrevBlockHash) == 0 {
break
}
}
}
return string(org.Prefix) + "." + strconv.Itoa(code) + "." + "1", nil
}