-
Notifications
You must be signed in to change notification settings - Fork 9
/
blockchain.go
1670 lines (1415 loc) · 48.2 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
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package blockchain
import (
"bytes"
"container/list"
"encoding/binary"
"errors"
"fmt"
"math/big"
sync "sync"
"time"
"github.com/filefilego/filefilego/block"
"github.com/filefilego/filefilego/common/currency"
"github.com/filefilego/filefilego/common/hexutil"
"github.com/filefilego/filefilego/crypto"
"github.com/filefilego/filefilego/database"
"github.com/filefilego/filefilego/node/protocols/messages"
"github.com/filefilego/filefilego/search"
"github.com/filefilego/filefilego/transaction"
log "github.com/sirupsen/logrus"
"github.com/syndtr/goleveldb/leveldb"
"github.com/syndtr/goleveldb/leveldb/util"
"google.golang.org/protobuf/proto"
)
const (
addressPrefix = "ad"
blockPrefix = "bl"
lastBlockPrefix = "last_block"
blockNumberPrefix = "bn"
addressTransactionPrefix = "atx"
transactionPrefix = "tx"
nodePrefix = "nd"
fileNodePrefix = "fn"
contractPrefix = "co"
contractFeesReleasePrefix = "rf"
nodeNodesPrefix = "nn"
channelPrefix = "ch"
channelsCountPrefix = "cc_cnt"
channelsNodesCountPrefix = "cnc"
)
var (
// ChannelCreationFeesFFG required amount to register a channel.
ChannelCreationFeesFFG = int64(400)
// RemainingChannelOperationFeesMiliFFG any other channel node item creation fees.
RemainingChannelOperationFeesMiliFFG = int64(100)
)
// Interface wraps the functionality of a blockchain.
type Interface interface {
GetBlocksFromPool() []block.Block
PutBlockPool(block block.Block) error
DeleteFromBlockPool(block block.Block) error
PutMemPool(tx transaction.Transaction) error
DeleteFromMemPool(tx transaction.Transaction) error
GetTransactionsFromPool() []transaction.Transaction
SaveBlockInDB(blck block.Block) error
GetBlockByHash(blockHash []byte) (block.Block, error)
GetNounceFromMemPool(address []byte) uint64
GetAddressState(address []byte) (AddressState, error)
UpdateAddressState(address []byte, state AddressState) error
CloseDB() error
IncrementHeightBy(h uint64)
GetHeight() uint64
GetLastBlockHash() []byte
PerformStateUpdateFromBlock(validBlock block.Block) error
GetBlockByNumber(blockNumber uint64) (*block.Block, error)
GetLastBlockUpdatedAt() int64
GetTransactionByHash(hash []byte) ([]transaction.Transaction, []uint64, error)
GetAddressTransactions(address []byte, currentPage, limit int) ([]transaction.Transaction, []uint64, []int64, error)
GetChannels(currentPage, pageSize int, order string) ([]*NodeItem, error)
GetChannelsCount() uint64
GetChildNodeItems(nodeHash []byte, currentPage, pageSize int, order string) ([]*NodeItem, uint64, error)
GetNodeItem(nodeHash []byte) (*NodeItem, error)
GetParentNodeItem(nodeHash []byte) (*NodeItem, error)
GetDownloadContractInTransactionDataTransactionHash(contractHash []byte) ([]DownloadContractInTransactionDataTxHash, error)
GetReleasedFeesOfDownloadContractInTransactionData(contractHash []byte) ([]DownloadContractInTransactionDataTxHash, error)
GetNodeFileItemFromFileHash(fileHash []byte) ([]*NodeItem, error)
GetFilesFromEntryOrFolderRecursively(entryOrFolderHash []byte, currentPage, pageSize int, order string) ([]FileMetadata, error)
}
// Blockchain represents a blockchain structure.
type Blockchain struct {
db database.Database
search search.IndexSearcher
blockPool map[string]block.Block
bmu sync.RWMutex
memPool map[string]transaction.Transaction
tmu sync.RWMutex
height uint64
hmu sync.RWMutex
genesisBlockHash []byte
updatingBlockchainStateMux sync.RWMutex
updatingBlockchainState bool
// lastBlockUpdateAt used to trigger syncing
lastBlockUpdateAt int64
lastBlockUpdateMu sync.RWMutex
}
// New creates a new blockchain instance.
func New(db database.Database, search search.IndexSearcher, genesisBlockHash []byte) (*Blockchain, error) {
if db == nil {
return nil, errors.New("db is nil")
}
if search == nil {
return nil, errors.New("search is nil")
}
if len(genesisBlockHash) == 0 {
return nil, errors.New("genesis block hash is empty")
}
b := &Blockchain{
db: db,
search: search,
blockPool: make(map[string]block.Block),
memPool: make(map[string]transaction.Transaction),
genesisBlockHash: make([]byte, len(genesisBlockHash)),
}
copy(b.genesisBlockHash, genesisBlockHash)
return b, nil
}
// InitOrLoad intializes or loads the blockchain from the database.
func (b *Blockchain) InitOrLoad(verifyAllBlocks bool) error {
lastBlockHash := b.GetLastBlockHash()
if len(lastBlockHash) == 0 {
// reset height
b.SetHeight(0)
// init blockchain
genesisBlock, err := block.GetGenesisBlock()
if err != nil {
return fmt.Errorf("failed to get genesis block: %w", err)
}
log.Info("genesis block hash: ", hexutil.Encode(genesisBlock.Hash))
err = b.PerformStateUpdateFromBlock(*genesisBlock)
if err != nil {
return fmt.Errorf("failed to perform block state update: %w", err)
}
return nil
}
if !verifyAllBlocks {
foundBlock, err := b.GetBlockByHash(lastBlockHash)
if err != nil {
return fmt.Errorf("failed to get block: %v with error: %w", hexutil.Encode(lastBlockHash), err)
}
b.SetHeight(foundBlock.Number)
return nil
}
// load blockchain and verify
for {
foundBlock, err := b.GetBlockByHash(lastBlockHash)
if err != nil {
return fmt.Errorf("failed to get block: %v with error: %w", hexutil.Encode(lastBlockHash), err)
}
ok, err := foundBlock.Validate()
if err != nil || !ok {
return fmt.Errorf("failed to verify block: %s : %w", hexutil.Encode(lastBlockHash), err)
}
lastBlockHash = make([]byte, len(foundBlock.PreviousBlockHash))
copy(lastBlockHash, foundBlock.PreviousBlockHash)
// if we reach the genesis block
if bytes.Equal(lastBlockHash, []byte{0}) {
break
}
b.IncrementHeightBy(1)
}
return nil
}
// GetLastBlockUpdatedAt returns the timestamp of the last blockchain update from a block.
func (b *Blockchain) GetLastBlockUpdatedAt() int64 {
b.lastBlockUpdateMu.RLock()
defer b.lastBlockUpdateMu.RUnlock()
return b.lastBlockUpdateAt
}
// SetHeight sets the height of the blockchain.
func (b *Blockchain) SetHeight(h uint64) {
b.hmu.Lock()
defer b.hmu.Unlock()
b.height = h
}
// SetLastBlockHash sets the last block hash.
func (b *Blockchain) SetLastBlockHash(data []byte) error {
if err := b.db.Put([]byte(lastBlockPrefix), data); err != nil {
return fmt.Errorf("failed to update last block hash in db: %w", err)
}
return nil
}
// GetLastBlockHash gets the last block hash.
func (b *Blockchain) GetLastBlockHash() []byte {
data, err := b.db.Get([]byte(lastBlockPrefix))
if err != nil || len(data) == 0 {
return nil
}
return data
}
// IncrementHeightBy increments the blockchain height by the given number.
func (b *Blockchain) IncrementHeightBy(h uint64) {
b.hmu.Lock()
defer b.hmu.Unlock()
b.height += h
}
// GetHeight gets the height of the blockchain.
func (b *Blockchain) GetHeight() uint64 {
b.hmu.RLock()
defer b.hmu.RUnlock()
return b.height
}
// GetBlocksFromPool get all the block from blockpool.
func (b *Blockchain) GetBlocksFromPool() []block.Block {
b.bmu.RLock()
defer b.bmu.RUnlock()
blocks := make([]block.Block, 0, len(b.blockPool))
for _, blc := range b.blockPool {
blocks = append(blocks, blc)
}
return blocks
}
// indexBlockHashByBlockNumber indexes the blockHash by the block number so we can query db by block numbers.
func (b *Blockchain) indexBlockHashByBlockNumber(blockHash []byte, blockNumber uint64) error {
blockNumberBytes := make([]byte, 8)
binary.BigEndian.PutUint64(blockNumberBytes, blockNumber)
if err := b.db.Put(append([]byte(blockNumberPrefix), blockNumberBytes...), blockHash); err != nil {
return fmt.Errorf("failed to save block number and hash into db: %w", err)
}
return nil
}
// indexBlockTransactions indexes the transactions of blocks so they can be retrieved by hash.
// block number is included in the key and the value is an empty byte.
// use an iterator to find the transaction hashes, in this way its possible to index coinbase txs.
func (b *Blockchain) indexBlockTransactions(validBlock block.Block) error {
blockNumberBytes := make([]byte, 8)
binary.BigEndian.PutUint64(blockNumberBytes, validBlock.Number)
batch := new(leveldb.Batch)
for _, v := range validBlock.Transactions {
prefixWithTransactionHash := append([]byte(transactionPrefix), v.Hash...)
batch.Put(append(prefixWithTransactionHash, blockNumberBytes...), []byte{})
}
err := b.db.Write(batch, nil)
if err != nil {
return fmt.Errorf("failed to write batch of block transactions: %w", err)
}
return nil
}
// GetTransactionByHash returns a list of transactions found in db.
func (b *Blockchain) GetTransactionByHash(hash []byte) ([]transaction.Transaction, []uint64, error) {
prefixWithTransacton := append([]byte(transactionPrefix), hash...)
iter := b.db.NewIterator(util.BytesPrefix(prefixWithTransacton), nil)
blockNumbers := make([]uint64, 0)
for iter.Next() {
key := iter.Key()
blockNumberBytes := key[len(prefixWithTransacton):]
blockNumbers = append(blockNumbers, binary.BigEndian.Uint64(blockNumberBytes))
}
iter.Release()
err := iter.Error()
if err != nil {
return nil, nil, fmt.Errorf("failed to release transaction by hash iterator: %w", err)
}
// get the blocks
transactions := make([]transaction.Transaction, 0)
for _, blckNum := range blockNumbers {
block, err := b.GetBlockByNumber(blckNum)
if err != nil {
return nil, nil, fmt.Errorf("failed to get block %d : %w", blckNum, err)
}
for _, tx := range block.Transactions {
if bytes.Equal(hash, tx.Hash) {
transactions = append(transactions, tx)
}
}
}
if len(transactions) != len(blockNumbers) {
return nil, nil, errors.New("transactions list length is not equal to block numbers length")
}
return transactions, blockNumbers, nil
}
// indexTransactionsByAddress indexes the transaction by the addresses "from" and "to".
// indexing is based on the following key: prefix_address_blocknumber_transactionIndex
func (b *Blockchain) indexTransactionsByAddresses(validBlock block.Block) error {
blockNumberBytes := make([]byte, 8)
binary.BigEndian.PutUint64(blockNumberBytes, validBlock.Number)
batch := new(leveldb.Batch)
for i, v := range validBlock.Transactions {
indexBytes := make([]byte, 8)
binary.BigEndian.PutUint64(indexBytes, uint64(i))
fromAddr, _ := hexutil.Decode(v.From)
toAddr, _ := hexutil.Decode(v.To)
prefixWithFromAddress := append([]byte(addressTransactionPrefix), fromAddr...)
prefixWithToAddress := append([]byte(addressTransactionPrefix), toAddr...)
// nolint:gocritic
prefixWithFromAddressBlocknumber := append(prefixWithFromAddress, blockNumberBytes...)
// nolint:gocritic
prefixWithToAddressBlocknumber := append(prefixWithToAddress, blockNumberBytes...)
batch.Put(append(prefixWithFromAddressBlocknumber, indexBytes...), v.Hash)
batch.Put(append(prefixWithToAddressBlocknumber, indexBytes...), v.Hash)
}
err := b.db.Write(batch, nil)
if err != nil {
return fmt.Errorf("failed to write batch of address and transactions: %w", err)
}
return nil
}
// GetAddressTransactions returns a list of transaction given the address.
func (b *Blockchain) GetAddressTransactions(address []byte, currentPage, pageSize int) ([]transaction.Transaction, []uint64, []int64, error) {
if currentPage < 0 {
currentPage = 0
}
if pageSize == 0 {
pageSize = 10
} else if pageSize > 100 {
pageSize = 100
}
start := (currentPage) * pageSize
if start < 0 {
start = 0
}
limit := pageSize
prefixWithAddress := append([]byte(addressTransactionPrefix), address...)
iter := b.db.NewIterator(util.BytesPrefix(prefixWithAddress), nil)
blockNumbers := make([]uint64, 0)
txIndexes := make([]int64, 0)
i := 0
// go to last so we can start reading backwards
// we need to go back to the last element so we can include it
// in the transactions list.
if iter.Last() {
key := iter.Key()
i++
if len(key) != 0 && i > start {
blockNumAndTxIndex := key[len(prefixWithAddress):]
blockNumbers = append(blockNumbers, binary.BigEndian.Uint64(blockNumAndTxIndex[:8]))
txIndexes = append(txIndexes, int64(binary.BigEndian.Uint64(blockNumAndTxIndex[8:])))
limit--
}
}
for iter.Prev() {
i++
if limit == 0 {
break
}
if i < start {
continue
}
key := iter.Key()
if len(key) == 0 {
break
}
blockNumAndTxIndex := key[len(prefixWithAddress):]
blockNumbers = append(blockNumbers, binary.BigEndian.Uint64(blockNumAndTxIndex[:8]))
txIndexes = append(txIndexes, int64(binary.BigEndian.Uint64(blockNumAndTxIndex[8:])))
limit--
}
iter.Release()
err := iter.Error()
if err != nil {
return nil, nil, nil, fmt.Errorf("iterator error while getting transactions: %w", err)
}
transactions := make([]transaction.Transaction, len(txIndexes))
blockTimestamps := make([]int64, len(blockNumbers))
for i, blockNum := range blockNumbers {
validBlock, err := b.GetBlockByNumber(blockNum)
if err != nil {
return nil, nil, nil, fmt.Errorf("failed to get block number %d in get transactions by address: %w", blockNum, err)
}
blockTimestamps[i] = validBlock.Timestamp
transactions[i] = validBlock.Transactions[txIndexes[i]]
}
return transactions, blockNumbers, blockTimestamps, nil
}
// GetBlockByNumber returns a block by number.
func (b *Blockchain) GetBlockByNumber(blockNumber uint64) (*block.Block, error) {
blockNumberBytes := make([]byte, 8)
binary.BigEndian.PutUint64(blockNumberBytes, blockNumber)
blockHash, err := b.db.Get(append([]byte(blockNumberPrefix), blockNumberBytes...))
if err != nil {
return nil, fmt.Errorf("failed to get block hash by block number: %w", err)
}
foundBlock, err := b.GetBlockByHash(blockHash)
if err != nil {
return nil, fmt.Errorf("failed to get block by hash: %w", err)
}
return &foundBlock, nil
}
func (b *Blockchain) setUpdatingBlockchainState(updating bool) {
b.updatingBlockchainStateMux.Lock()
defer b.updatingBlockchainStateMux.Unlock()
b.updatingBlockchainState = updating
}
func (b *Blockchain) getUpdatingBlockchainState() bool {
b.updatingBlockchainStateMux.Lock()
defer b.updatingBlockchainStateMux.Unlock()
return b.updatingBlockchainState
}
// PutBlockPool adds a block to blockPool.
func (b *Blockchain) PutBlockPool(block block.Block) error {
currentHeight := b.GetHeight()
if block.Number < currentHeight {
return nil
}
b.bmu.Lock()
blockHash := hexutil.Encode(block.Hash)
b.blockPool[blockHash] = block
b.bmu.Unlock()
// make other goroutines to return while update operation is being performed.
if b.getUpdatingBlockchainState() {
return nil
}
b.setUpdatingBlockchainState(true)
defer b.setUpdatingBlockchainState(false)
for {
nextBlockFound := false
lastBlockHash := b.GetLastBlockHash()
if lastBlockHash == nil {
return errors.New("last block hash is nil")
}
blocskPool := b.GetBlocksFromPool()
for _, blck := range blocskPool {
// remove old blocks from pool
if blck.Number < currentHeight {
if err := b.DeleteFromBlockPool(blck); err != nil {
log.Errorf("failed to delete block %s from blockpool: %v", hexutil.Encode(blck.Hash), err)
}
continue
}
if bytes.Equal(blck.PreviousBlockHash, lastBlockHash) {
nextBlockFound = true
if err := b.PerformStateUpdateFromBlock(blck); err != nil {
log.Errorf("failed to perform blockchain update from block %s : %v", hexutil.Encode(blck.Hash), err)
}
if err := b.DeleteFromBlockPool(blck); err != nil {
log.Errorf("failed to delete block %s from blockpool: %v", hexutil.Encode(blck.Hash), err)
}
}
}
if !nextBlockFound {
break
}
}
return nil
}
// DeleteFromBlockPool deletes a block from mempool.
func (b *Blockchain) DeleteFromBlockPool(block block.Block) error {
b.bmu.Lock()
defer b.bmu.Unlock()
blockHash := hexutil.Encode(block.Hash)
delete(b.blockPool, blockHash)
return nil
}
// addBalanceTo adds balance to address.
func (b *Blockchain) addBalanceTo(address []byte, amount *big.Int) error {
zeroBig := big.NewInt(0)
if amount.Cmp(zeroBig) == -1 {
return errors.New("amount is negative")
}
state, err := b.GetAddressState(address)
// address has no balance
if err != nil {
state.SetBalance(big.NewInt(0))
state.SetNounce(0)
}
balance, err := state.GetBalance()
if err != nil {
return fmt.Errorf("failed to get balance: %w", err)
}
state.SetBalance(balance.Add(balance, amount))
err = b.UpdateAddressState(address, state)
if err != nil {
return fmt.Errorf("failed to update balance state: %w", err)
}
return nil
}
// subBalanceFrom subtracts balance from address.
func (b *Blockchain) subBalanceFrom(address []byte, amount *big.Int, nounce uint64) error {
zeroBig := big.NewInt(0)
if amount.Cmp(zeroBig) == -1 {
return errors.New("amount is negative")
}
state, err := b.GetAddressState(address)
// address has no balance
if err != nil {
return fmt.Errorf("address has no balance: %w", err)
}
balance, err := state.GetBalance()
if err != nil {
return fmt.Errorf("failed to get balance: %w", err)
}
if balance.Cmp(amount) < 0 {
return errors.New("failed to subtract: amount is greater than balance")
}
state.SetBalance(balance.Sub(balance, amount))
state.SetNounce(nounce)
err = b.UpdateAddressState(address, state)
if err != nil {
return fmt.Errorf("failed to update balance state: %w", err)
}
return nil
}
// PerformAddressStateUpdate performs state update.
// This function should be able to rollback to previous state in case of failure.
// APPLYING OPERATIONS ON BIG INTS MODIFIES THE UNDERLYING DATA.
func (b *Blockchain) PerformAddressStateUpdate(transaction transaction.Transaction, verifierAddr []byte, isCoinbase bool) error {
ok, err := transaction.Validate()
if err != nil || !ok {
return fmt.Errorf("failed to validate transaction: %w", err)
}
txFees, err := hexutil.DecodeBig(transaction.TransactionFees)
if err != nil {
return fmt.Errorf("failed to decode transaction fees: %w", err)
}
fromAddrBytes, err := hexutil.Decode(transaction.From)
if err != nil {
return fmt.Errorf("failed to decode from address: %w", err)
}
fromState, err := b.GetAddressState(fromAddrBytes)
if err != nil {
// if from is not available, create a zero state
fromState.SetNounce(0)
fromState.SetBalance(big.NewInt(0))
if err := b.UpdateAddressState(fromAddrBytes, fromState); err != nil {
return fmt.Errorf("failed to initialize zero state for `from` address: %w", err)
}
}
fromAddressNounceDB, err := fromState.GetNounce()
if err != nil {
return fmt.Errorf("failed to get nounce of address state: %w", err)
}
// if not coinbase tx, then subtract the amount from the account
if !isCoinbase {
fromAddressNounceTX := hexutil.DecodeBigFromBytesToUint64(transaction.Nounce)
if fromAddressNounceTX != fromAddressNounceDB+1 {
return fmt.Errorf("the nounce %d in transaction is not the next nounce of database value: %d", fromAddressNounceTX, fromAddressNounceDB)
}
txValue, err := hexutil.DecodeBig(transaction.Value)
if err != nil {
return fmt.Errorf("failed to decode transaction value: %w", err)
}
totalFees := txValue.Add(txValue, txFees)
err = b.subBalanceFrom(fromAddrBytes, totalFees, fromAddressNounceTX)
if err != nil {
return fmt.Errorf("failed to subtract total value from address: %w", err)
}
}
toAddrBytes, err := hexutil.Decode(transaction.To)
if err != nil {
return fmt.Errorf("failed to decode to address: %w", err)
}
txValue, err := hexutil.DecodeBig(transaction.Value)
if err != nil {
return fmt.Errorf("failed to decode transaction value: %w", err)
}
err = b.addBalanceTo(toAddrBytes, txValue)
if err != nil {
return fmt.Errorf("failed to add amount to balance: %w", err)
}
err = b.addBalanceTo(verifierAddr, txFees)
if err != nil {
return fmt.Errorf("failed to add amount to verifier's balance: %w", err)
}
err = b.performStateUpdateFromDataPayload(&transaction)
if err != nil {
log.Errorf("failed to perform state update from tx data payload: %v", err)
}
return nil
}
// performStateUpdateFromDataPayload performs updates from the transaction data.
// operations allowed are related to updating blockchain settings and channel operations.
// there could be arbitrary data in the transaction data field so trying to unmarshal first and
// if failed then just return without any error.
func (b *Blockchain) performStateUpdateFromDataPayload(tx *transaction.Transaction) error {
dataPayload := transaction.DataPayload{}
err := proto.Unmarshal(tx.Data, &dataPayload)
if err != nil {
return nil
}
// create a data download contract
if dataPayload.Type == transaction.DataType_DATA_CONTRACT {
downloadContracts := messages.DownloadContractsHashesProto{}
err := proto.Unmarshal(dataPayload.Payload, &downloadContracts)
if err != nil {
return nil
}
for _, v := range downloadContracts.Contracts {
err = b.saveContractFromTransactionDataPayload(v, tx.Hash)
if err != nil {
return fmt.Errorf("failed to save contract in db: %w", err)
}
}
}
// release fees to file hoster given the contract
if dataPayload.Type == transaction.DataType_DATA_CONTRACT_RELEASE_HOSTER_FEES {
downloadContracts := messages.DownloadContractsHashesProto{}
err := proto.Unmarshal(dataPayload.Payload, &downloadContracts)
if err != nil {
return nil
}
for _, v := range downloadContracts.Contracts {
err = b.releaseFeesContractFromTransactionDataPayload(v, tx.Hash)
if err != nil {
return fmt.Errorf("failed to save release fees contract in db: %w", err)
}
}
}
// support creating multiple nodes
if dataPayload.Type == transaction.DataType_CREATE_NODE {
nodesEnvelope := NodeItems{}
err := proto.Unmarshal(dataPayload.Payload, &nodesEnvelope)
if err != nil {
return nil
}
txFees, err := hexutil.DecodeBig(tx.TransactionFees)
if err != nil {
return fmt.Errorf("failed to get the transaction fee value while updating tx data payload: %w", err)
}
totalActionsFees := CalculateChannelActionsFees(nodesEnvelope.Nodes)
if txFees.Cmp(totalActionsFees) == -1 {
return fmt.Errorf("total cost of channel actions (%s) are higher than the supplied transaction fee (%s)", totalActionsFees.Text(10), txFees.Text(10))
}
for _, node := range nodesEnvelope.Nodes {
node.Enabled = true
fromBytes, _ := hexutil.Decode(tx.From)
node.Owner = fromBytes
if node.Timestamp <= 0 {
return fmt.Errorf("timestamp is empty")
}
if node.NodeType == NodeItemType_CHANNEL {
if node.Name == "" {
return errors.New("channel node name is empty")
}
data := bytes.Join(
[][]byte{
fromBytes,
[]byte(node.Name),
},
[]byte{},
)
node.ParentHash = []byte{}
node.NodeHash = crypto.Sha256(data)
err = b.saveNode(node)
if err != nil {
return fmt.Errorf("failed to create channel node: %w", err)
}
err = b.saveAsChannel(node.NodeHash)
if err != nil {
return fmt.Errorf("failed add to channel list: %w", err)
}
} else {
if len(node.ParentHash) == 0 {
return fmt.Errorf("parent hash of node is empty")
}
data := bytes.Join(
[][]byte{
node.ParentHash,
[]byte(node.Name),
},
[]byte{},
)
node.NodeHash = crypto.Sha256(data)
// get parent
parentNode, err := b.GetNodeItem(node.ParentHash)
if err != nil {
return fmt.Errorf("failed to get parent of node %s : %w", hexutil.Encode(node.ParentHash), err)
}
// check if allowed to insert node to parent
ok, err := applyChannelStructureConstraints(parentNode, node)
if err != nil || !ok {
return fmt.Errorf("failed to satisfy node structure constraints: %w", err)
}
var rootNodeItem *NodeItem
// if parent is root
if parentNode.NodeType == NodeItemType_CHANNEL {
rootNodeItem = parentNode
} else {
// traverse back to find root
rootItem, err := b.GetRootNodeItem(parentNode.NodeHash)
if err != nil {
return fmt.Errorf("failed to get root node item: %w", err)
}
rootNodeItem = rootItem
}
// get permissions to see if allowed
owner, admin, poster := b.GetPermissionFromRootNode(rootNodeItem, fromBytes)
if err != nil {
return fmt.Errorf("failed to retrieve root node to get permissions: %w", err)
}
if !owner && !admin && !poster && node.NodeType != NodeItemType_OTHER {
return errors.New("only `other` nodes can be added by guest")
}
// if poster allow only to add entry, dir, file and other
if poster && node.NodeType == NodeItemType_SUBCHANNEL {
return errors.New("poster can't create channel and subchannel")
}
err = b.saveNode(node)
if err != nil {
return fmt.Errorf("failed to create node: %w", err)
}
err = b.saveNodeAsChildNode(parentNode.NodeHash, node.NodeHash, uint8(node.NodeType))
if err != nil {
return fmt.Errorf("failed to save node child: %w", err)
}
}
nodeDescription := ""
if node.Description != nil {
nodeDescription = *node.Description
}
indexItem := search.IndexItem{
Hash: hexutil.Encode(node.NodeHash),
Type: int32(node.NodeType),
Name: node.Name,
Description: nodeDescription,
}
err = b.search.Index(indexItem)
if err != nil {
return fmt.Errorf("failed to index item into search engine: %w", err)
}
}
}
return nil
}
// PerformStateUpdateFromBlock performs updates from a block.
func (b *Blockchain) PerformStateUpdateFromBlock(validBlock block.Block) error {
_, err := b.GetBlockByHash(validBlock.Hash)
if err == nil {
return errors.New("block is already within the blockchain")
}
// if the block is not genesis block then validate the previous block
isGenesisBlock := bytes.Equal(b.genesisBlockHash, validBlock.Hash)
if !isGenesisBlock {
blockchainHeight := b.GetHeight()
if validBlock.Number <= blockchainHeight {
return fmt.Errorf("block: %d can't be smaller or equal to the blockchain height: %d", validBlock.Number, blockchainHeight)
}
previousBlock, err := b.GetBlockByHash(validBlock.PreviousBlockHash)
if err != nil {
return fmt.Errorf("previous block not found in database: %w", err)
}
if previousBlock.Number+1 != validBlock.Number {
return fmt.Errorf("block number doesn't match the continuation of previous block: current: %d, previous: %d", validBlock.Number, previousBlock.Number)
}
if validBlock.Timestamp < previousBlock.Timestamp {
return fmt.Errorf("previous block timestamp %d is bigger than the current block %d", previousBlock.Timestamp, validBlock.Timestamp)
}
}
coinbaseTx, err := validBlock.GetAndValidateCoinbaseTransaction()
if err != nil {
return fmt.Errorf("failed to get/validate coinbase transaction: %w", err)
}
verifierAddr, err := crypto.RawPublicToAddressBytes(coinbaseTx.PublicKey)
if err != nil {
return fmt.Errorf("failed to get address of verifier: %w", err)
}
for _, tx := range validBlock.Transactions {
isCoinbase, err := coinbaseTx.Equals(tx)
if err != nil {
return fmt.Errorf("failed to compare coinbase transaction: %w", err)
}
err = b.PerformAddressStateUpdate(tx, verifierAddr, isCoinbase)
if err != nil {
log.Errorf("failed to update the state of blockchain: %v", err)
_ = b.DeleteFromMemPool(tx)
continue
}
if !isCoinbase {
err = b.DeleteFromMemPool(tx)
if err != nil {
log.Warnf("failed to delete transaction from mempool: %v", err)
}
}
}
if !isGenesisBlock {
b.IncrementHeightBy(1)
}
err = b.SetLastBlockHash(validBlock.Hash)
if err != nil {
return fmt.Errorf("failed to update last block hash in db: %w", err)
}
err = b.SaveBlockInDB(validBlock)
if err != nil {
return fmt.Errorf("failed to save genesis block in DB: %w", err)
}
err = b.indexBlockHashByBlockNumber(validBlock.Hash, validBlock.Number)
if err != nil {
return fmt.Errorf("failed to index block hash by block number: %w", err)
}
err = b.indexTransactionsByAddresses(validBlock)
if err != nil {
return fmt.Errorf("failed to index transactions by address: %w", err)
}
err = b.indexBlockTransactions(validBlock)
if err != nil {
return fmt.Errorf("failed to index block transactions: %w", err)
}
b.lastBlockUpdateMu.Lock()
b.lastBlockUpdateAt = time.Now().Unix()
b.lastBlockUpdateMu.Unlock()
return nil
}
// GetNounceFromMemPool get the nounce of an address from mempool.
func (b *Blockchain) GetNounceFromMemPool(address []byte) uint64 {
b.tmu.RLock()
defer b.tmu.RUnlock()
tmp := uint64(0)
for _, v := range b.memPool {
if v.From == hexutil.Encode(address) {
nounce := hexutil.DecodeBigFromBytesToUint64(v.Nounce)
if nounce > tmp {
tmp = nounce
}
}
}
return tmp
}
// PutMemPool adds a transaction to mempool.
// validation of transaction should be done outside this function.
func (b *Blockchain) PutMemPool(tx transaction.Transaction) error {
b.tmu.Lock()
defer b.tmu.Unlock()
for idx, transaction := range b.memPool {
// transaction is already in mempool with this nounce
// pick the one with higher fee
if bytes.Equal(transaction.Nounce, tx.Nounce) && transaction.From == tx.From {
txFees, err := hexutil.DecodeBig(tx.TransactionFees)
if err != nil {
return fmt.Errorf("failed to decode transaction fees: %w", err)
}
txFeesInMempool, err := hexutil.DecodeBig(transaction.TransactionFees)
if err != nil {
return fmt.Errorf("failed to decode transaction fees from mempool: %w", err)
}
if txFees.Cmp(txFeesInMempool) == 1 {
b.memPool[idx] = tx
return nil
}
}
}
txHash := hexutil.Encode(tx.Hash)
b.memPool[txHash] = tx
return nil
}
// DeleteFromMemPool deletes a transaction from mempool.
func (b *Blockchain) DeleteFromMemPool(tx transaction.Transaction) error {
b.tmu.Lock()
defer b.tmu.Unlock()
txHash := hexutil.Encode(tx.Hash)
delete(b.memPool, txHash)
return nil
}
// GetTransactionsFromPool get all the transactions from mempool.