This repository has been archived by the owner on Nov 15, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 192
/
Blockchain.py
1149 lines (877 loc) · 39.4 KB
/
Blockchain.py
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
import pytz
import asyncio
import binascii
import struct
import traceback
import os
import json
from neo.VM.VMState import VMStateStr
from contextlib import suppress
from neo.VM import InteropService
from itertools import groupby
from datetime import datetime
from neo.Storage.Common.DataCache import TrackState
from neo.Network.common import Events
import neo.Core.Block
from neo.Core.TX.Transaction import TransactionOutput
from neo.Core.AssetType import AssetType
from neo.Core.Cryptography.Crypto import Crypto
from neo.Core.Header import Header
from neo.Core.TX.RegisterTransaction import RegisterTransaction
from neo.Core.TX.MinerTransaction import MinerTransaction
from neo.Core.TX.IssueTransaction import IssueTransaction
from neo.Core.TX.Transaction import Transaction, TransactionType
from neo.Core.Witness import Witness
from neo.Core.State.UnspentCoinState import UnspentCoinState
from neo.Core.State.AccountState import AccountState
from neo.Core.State.CoinState import CoinState
from neo.Core.State.ContractState import ContractState
from neo.Core.State.StorageItem import StorageItem
from neo.Core.State.SpentCoinState import SpentCoinState, SpentCoinItem, SpentCoin
from neo.Core.State.AssetState import AssetState
from neo.Core.State.ValidatorState import ValidatorState
from neo.Core.IO.BinaryReader import BinaryReader
from neo.IO.MemoryStream import StreamManager
from neo.logging import log_manager
from neo.Settings import settings
from neo.Core.Fixed8 import Fixed8
from neo.Core.Cryptography.ECCurve import ECDSA
from neo.Core.UInt256 import UInt256
from neo.Core.UInt160 import UInt160
from neo.Core.IO.BinaryWriter import BinaryWriter
from neo.SmartContract.StateMachine import StateMachine
from neo.SmartContract.Contract import Contract
from neo.SmartContract.ApplicationEngine import ApplicationEngine
from neo.Storage.Common.DBPrefix import DBPrefix
from neo.Storage.Common.CachedScriptTable import CachedScriptTable
from neo.Storage.Interface.DBInterface import DBInterface
from neo.Storage.Interface.DBProperties import DBProperties
from neo.SmartContract import TriggerType
from neo.VM.OpCode import PUSHF, PUSHT
from functools import lru_cache
from neo.Network.common import msgrouter
from neo.EventHub import events
from neo.Network.common import blocking_prompt as prompt
from neo.Network.common import wait_for
from typing import Tuple
import neo.Storage.Implementation.DBFactory as DBFactory
logger = log_manager.getLogger()
class Blockchain:
SECONDS_PER_BLOCK = 15
DECREMENT_INTERVAL = 2000000
GENERATION_AMOUNT = [8, 7, 6, 5, 4, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
_db = None
_blockchain = None
_validators = []
_genesis_block = None
_instance = None
_blockrequests = set()
_paused = False
_disposed = False
_verify_blocks = False
_header_index = []
_block_cache = {}
_current_block_height = 0
_stored_header_count = 0
_persisting_block = None
TXProcessed = 0
BlockSearchTries = 0
_sysversion = b'schema v.0.8.5'
CACHELIM = 4000
CMISSLIM = 5
LOOPTIME = .1
PersistCompleted = Events()
Notify = Events()
# debug:
_previous_blockid = None
def __init__(self, db, skip_version_check=False, skip_header_check=False):
self._db = db
self._header_index = []
self._header_index.append(Blockchain.GenesisBlock().Header.Hash.ToBytes())
self.TXProcessed = 0
version = self._db.get(DBPrefix.SYS_Version)
if skip_version_check:
self._db.write(DBPrefix.SYS_Version, self._sysversion)
version = self._sysversion
if version == self._sysversion: # or in the future, if version doesn't equal the current version...
ba = bytearray(self._db.get(DBPrefix.SYS_CurrentBlock, 0))
self._current_block_height = int.from_bytes(ba[-4:], 'little')
if not skip_header_check:
ba = bytearray(self._db.get(DBPrefix.SYS_CurrentHeader, 0))
current_header_height = int.from_bytes(ba[-4:], 'little')
current_header_hash = bytes(ba[:64].decode('utf-8'), encoding='utf-8')
hashes = []
try:
with self._db.openIter(DBProperties(DBPrefix.IX_HeaderHashList)) as it:
for key, value in it:
ms = StreamManager.GetStream(value)
reader = BinaryReader(ms)
hlist = reader.Read2000256List()
key = int.from_bytes(key[-4:], 'little')
hashes.append({'k': key, 'v': hlist})
StreamManager.ReleaseStream(ms)
except Exception as e:
logger.info("Could not get stored header hash list: %s " % e)
if len(hashes):
hashes.sort(key=lambda x: x['k'])
genstr = Blockchain.GenesisBlock().Hash.ToBytes()
for hlist in hashes:
for hash in hlist['v']:
if hash != genstr:
self._header_index.append(hash)
self._stored_header_count += 1
if self._stored_header_count == 0:
logger.info("Current stored headers empty, re-creating from stored blocks...")
headers = []
logger.info('Recreate headers')
with self._db.openIter(DBProperties(DBPrefix.DATA_Block)) as it:
for key, value in it:
dbhash = bytearray(value)[8:]
headers.append(Header.FromTrimmedData(binascii.unhexlify(dbhash), 0))
headers.sort(key=lambda h: h.Index)
for h in headers:
if h.Index > 0:
self._header_index.append(h.Hash.ToBytes())
if len(headers):
self.OnAddHeader(headers[-1])
elif current_header_height > self._stored_header_count:
try:
hash = current_header_hash
targethash = self._header_index[-1]
newhashes = []
while hash != targethash:
header = self.GetHeader(hash)
newhashes.insert(0, header)
hash = header.PrevHash.ToBytes()
self.AddHeaders(newhashes)
except Exception as e:
pass
elif version is None:
wait_for(self.Persist(Blockchain.GenesisBlock()))
self._db.write(DBPrefix.SYS_Version, self._sysversion)
else:
logger.error("\n\n")
logger.warning("Database schema has changed from %s to %s.\n" % (version, self._sysversion))
logger.warning("You must either resync from scratch, or use the np-bootstrap command to bootstrap the chain.")
res = prompt("Type 'continue' to erase your current database and sync from new. Otherwise this program will exit:\n> ")
if res == 'continue':
with self._db.getBatch() as wb:
with self._db.openIter(DBProperties(include_value=False)) as it:
for key in it:
wb.delete(key)
wait_for(self.Persist(Blockchain.GenesisBlock()))
self._db.write(DBPrefix.SYS_Version, self._sysversion)
else:
raise Exception("Database schema changed")
@staticmethod
def StandbyValidators():
if len(Blockchain._validators) < 1:
vlist = settings.STANDBY_VALIDATORS
for pkey in settings.STANDBY_VALIDATORS:
Blockchain._validators.append(ECDSA.decode_secp256r1(pkey).G)
return Blockchain._validators
@staticmethod
@lru_cache(maxsize=2)
def SystemShare():
"""
Register AntShare.
Returns:
RegisterTransaction:
"""
amount = Fixed8.FromDecimal(sum(Blockchain.GENERATION_AMOUNT) * Blockchain.DECREMENT_INTERVAL)
owner = ECDSA.secp256r1().Curve.Infinity
admin = Crypto.ToScriptHash(PUSHT)
return RegisterTransaction([], [], AssetType.GoverningToken,
"[{\"lang\":\"zh-CN\",\"name\":\"小蚁股\"},{\"lang\":\"en\",\"name\":\"AntShare\"}]",
amount, 0, owner, admin)
@staticmethod
@lru_cache(maxsize=2)
def SystemCoin():
"""
Register AntCoin
Returns:
RegisterTransaction:
"""
amount = Fixed8.FromDecimal(sum(Blockchain.GENERATION_AMOUNT) * Blockchain.DECREMENT_INTERVAL)
owner = ECDSA.secp256r1().Curve.Infinity
precision = 8
admin = Crypto.ToScriptHash(PUSHF)
return RegisterTransaction([], [], AssetType.UtilityToken,
"[{\"lang\":\"zh-CN\",\"name\":\"小蚁币\"},{\"lang\":\"en\",\"name\":\"AntCoin\"}]",
amount, precision, owner, admin)
@staticmethod
def GenesisBlock():
"""
Create the GenesisBlock.
Returns:
BLock:
"""
prev_hash = UInt256(data=bytearray(32))
timestamp = int(datetime(2016, 7, 15, 15, 8, 21, tzinfo=pytz.utc).timestamp())
index = 0
consensus_data = 2083236893 # Pay tribute To Bitcoin
next_consensus = Blockchain.GetConsensusAddress(Blockchain.StandbyValidators())
script = Witness(bytearray(0), bytearray(PUSHT))
mt = MinerTransaction()
mt.Nonce = 2083236893
output = TransactionOutput(
Blockchain.SystemShare().Hash,
Blockchain.SystemShare().Amount,
Crypto.ToScriptHash(
Contract.CreateMultiSigRedeemScript(
int(len(Blockchain.StandbyValidators()) / 2) + 1,
Blockchain.StandbyValidators()
)
)
)
it = IssueTransaction([], [output], [], [script])
return neo.Core.Block.Block(prev_hash, timestamp, index, consensus_data, next_consensus, script,
[mt, Blockchain.SystemShare(), Blockchain.SystemCoin(), it], True)
def GetDB(self):
if self._db is not None:
return self._db
raise ('Database not defined')
@staticmethod
def Default() -> 'Blockchain':
"""
Get the default registered blockchain instance.
Returns:
obj: Blockchain based on the configured database backend.
"""
if Blockchain._instance is None:
Blockchain._instance = Blockchain(DBFactory.getBlockchainDB())
Blockchain.GenesisBlock().RebuildMerkleRoot()
return Blockchain._instance
@property
def CurrentBlockHash(self):
try:
return self._header_index[self._current_block_height]
except Exception as e:
logger.info("Could not get current block hash, returning none: %s ", e)
return None
@property
def CurrentHeaderHash(self):
return self._header_index[-1]
@property
def HeaderHeight(self):
height = len(self._header_index) - 1
return height
@property
def Height(self):
return self._current_block_height
@property
def CurrentBlock(self):
if self._persisting_block:
return self._persisting_block
return self.GetBlockByHeight(self.Height)
def AddBlock(self, block):
if not block.Hash.ToBytes() in self._block_cache:
self._block_cache[block.Hash.ToBytes()] = block
header_len = len(self._header_index)
if block.Index - 1 >= header_len:
return False
if block.Index == header_len:
if self._verify_blocks and not block.Verify():
return False
elif len(block.Transactions) < 1:
return False
self.AddHeader(block.Header)
return True
def AddBlockDirectly(self, block, do_persist_complete=True):
# Adds a block when importing, which skips adding
# the block header
if block.Index != self.Height + 1:
raise Exception("Invalid block")
self.Persist(block)
if do_persist_complete:
self.OnPersistCompleted(block)
def AddHeader(self, header):
return self.AddHeaders([header])
def AddHeaders(self, headers):
newheaders = []
count = 0
for header in headers:
if header.Index - 1 >= len(self._header_index) + count:
logger.info(
"header is greater than header index length: %s %s " % (header.Index, len(self._header_index)))
break
if header.Index < count + len(self._header_index):
continue
if self._verify_blocks and not header.Verify():
break
count = count + 1
newheaders.append(header)
if len(newheaders):
self.ProcessNewHeaders(newheaders)
return count
def ProcessNewHeaders(self, headers):
lastheader = headers[-1]
hashes = [h.Hash.ToBytes() for h in headers]
self._header_index.extend(hashes)
if lastheader is not None:
self.OnAddHeader(lastheader)
def OnAddHeader(self, header):
hHash = header.Hash.ToBytes()
with self._db.getBatch() as wb:
while header.Index - 2000 >= self._stored_header_count:
ms = StreamManager.GetStream()
w = BinaryWriter(ms)
headers_to_write = self._header_index[self._stored_header_count:self._stored_header_count + 2000]
w.Write2000256List(headers_to_write)
out = ms.ToArray()
StreamManager.ReleaseStream(ms)
wb.put(DBPrefix.IX_HeaderHashList + self._stored_header_count.to_bytes(4, 'little'), out)
self._stored_header_count += 2000
if self._db.get(DBPrefix.DATA_Block + hHash) is None:
wb.put(DBPrefix.DATA_Block + hHash, bytes(8) + header.ToArray())
wb.put(DBPrefix.SYS_CurrentHeader, hHash + header.Index.to_bytes(4, 'little'))
@property
def BlockRequests(self):
"""
Outstanding block requests.
Returns:
set:
"""
return self._blockrequests
def ResetBlockRequests(self):
self._blockrequests = set()
@staticmethod
def CalculateBonusIgnoreClaimed(inputs, ignore_claimed=True):
unclaimed = []
for hash, group in groupby(inputs, lambda x: x.PrevHash):
claimable = Blockchain.Default().GetUnclaimed(hash)
if claimable is None or len(claimable) < 1:
if ignore_claimed:
continue
else:
raise Exception("Error calculating bonus without ignoring claimed")
for coinref in group:
if coinref.PrevIndex in claimable:
claimed = claimable[coinref.PrevIndex]
unclaimed.append(claimed)
else:
if ignore_claimed:
continue
else:
raise Exception("Error calculating bonus without ignoring claimed")
return Blockchain.CalculateBonusInternal(unclaimed)
@staticmethod
def CalculateBonus(inputs, height_end):
unclaimed = []
for hash, group in groupby(inputs, lambda x: x.PrevHash):
tx, height_start = Blockchain.Default().GetTransaction(hash)
if tx is None:
raise Exception("Could Not calculate bonus")
if height_start == height_end:
continue
for coinref in group:
if coinref.PrevIndex >= len(tx.outputs) or tx.outputs[coinref.PrevIndex].AssetId != Blockchain.SystemShare().Hash:
raise Exception("Invalid coin reference")
spent_coin = SpentCoin(output=tx.outputs[coinref.PrevIndex], start_height=height_start,
end_height=height_end)
unclaimed.append(spent_coin)
return Blockchain.CalculateBonusInternal(unclaimed)
@staticmethod
def CalculateBonusInternal(unclaimed):
amount_claimed = Fixed8.Zero()
decInterval = Blockchain.DECREMENT_INTERVAL
genAmount = Blockchain.GENERATION_AMOUNT
genLen = len(genAmount)
for coinheight, group in groupby(unclaimed, lambda x: x.Heights):
amount = 0
ustart = int(coinheight.start / decInterval)
if ustart < genLen:
istart = coinheight.start % decInterval
uend = int(coinheight.end / decInterval)
iend = coinheight.end % decInterval
if uend >= genLen:
iend = 0
if iend == 0:
uend -= 1
iend = decInterval
while ustart < uend:
amount += (decInterval - istart) * genAmount[ustart]
ustart += 1
istart = 0
amount += (iend - istart) * genAmount[ustart]
endamount = Blockchain.Default().GetSysFeeAmountByHeight(coinheight.end - 1)
startamount = 0 if coinheight.start == 0 else Blockchain.Default().GetSysFeeAmountByHeight(
coinheight.start - 1)
amount += endamount - startamount
outputSum = 0
for spentcoin in group:
outputSum += spentcoin.Value.value
outputSum = outputSum / 100000000
outputSumFixed8 = Fixed8(int(outputSum * amount))
amount_claimed += outputSumFixed8
return amount_claimed
def OnNotify(self, notification):
self.Notify.on_change(notification)
def ContainsBlock(self, index):
if index <= self._current_block_height:
return True
return False
def ContainsTransaction(self, hash):
tx = self._db.get(DBPrefix.DATA_Transaction + hash.ToBytes())
return True if tx is not None else False
def GetHeader(self, hash):
if isinstance(hash, UInt256):
hash = hash.ToString().encode()
try:
out = bytearray(self._db.get(DBPrefix.DATA_Block + hash))
out = out[8:]
outhex = binascii.unhexlify(out)
return Header.FromTrimmedData(outhex, 0)
except TypeError as e2:
pass
except Exception as e:
logger.info("OTHER ERRROR %s " % e)
return None
def GetHeaderBy(self, height_or_hash):
hash = None
intval = None
try:
intval = int(height_or_hash)
except Exception as e:
pass
if intval is None and len(height_or_hash) == 64:
bhash = height_or_hash.encode('utf-8')
if bhash in self._header_index:
hash = bhash
elif intval is None and len(height_or_hash) == 66:
bhash = height_or_hash[2:].encode('utf-8')
if bhash in self._header_index:
hash = bhash
elif intval is not None and self.GetHeaderHash(intval) is not None:
hash = self.GetHeaderHash(intval)
if hash is not None:
return self.GetHeader(hash)
return None
def GetHeaderByHeight(self, height):
if len(self._header_index) <= height:
return False
hash = self._header_index[height]
return self.GetHeader(hash)
def GetHeaderHash(self, height):
if height < len(self._header_index) and height >= 0:
return self._header_index[height]
return None
def GetBlockHash(self, height):
"""
Get the block hash by its block height
Args:
height(int): height of the block to retrieve hash from.
Returns:
bytes: a non-raw block hash (e.g. b'6dd83ed8a3fc02e322f91f30431bf3662a8c8e8ebe976c3565f0d21c70620991', but not b'\x6d\xd8...etc'
"""
if self._current_block_height < height:
return
if len(self._header_index) <= height:
return
return self._header_index[height]
def GetSysFeeAmount(self, hash):
if type(hash) is UInt256:
hash = hash.ToBytes()
try:
value = self._db.get(DBPrefix.DATA_Block + hash)[0:8]
amount = struct.unpack("<d", value)[0]
return amount
except Exception as e:
logger.debug("Could not get sys fee: %s " % e)
return 0
def GetBlockByHeight(self, height):
"""
Get a block by its height.
Args:
height(int): the height of the block to retrieve.
Returns:
neo.Core.Block: block instance.
"""
hash = self.GetBlockHash(height)
if hash is not None:
return self.GetBlockByHash(hash)
def GetBlock(self, height_or_hash):
hash = None
intval = None
try:
intval = int(height_or_hash)
except Exception as e:
pass
if intval is None and len(height_or_hash) == 64:
if isinstance(height_or_hash, str):
bhash = height_or_hash.encode('utf-8')
else:
bhash = height_or_hash
if bhash in self._header_index:
hash = bhash
elif intval is None and len(height_or_hash) == 66:
bhash = height_or_hash[2:].encode('utf-8')
if bhash in self._header_index:
hash = bhash
elif intval is not None and self.GetBlockHash(intval) is not None:
hash = self.GetBlockHash(intval)
if hash is not None:
return self.GetBlockByHash(hash)
return None
def GetBlockByHash(self, hash):
try:
out = bytearray(self._db.get(DBPrefix.DATA_Block + hash))
out = out[8:]
outhex = binascii.unhexlify(out)
return neo.Core.Block.Block.FromTrimmedData(outhex)
except Exception as e:
logger.info("Could not get block %s " % e)
return None
def GetStates(self, prefix, classref):
return DBInterface(self._db, prefix, classref)
def GetAccountState(self, address, print_all_accounts=False):
if type(address) is str:
try:
address = address.encode('utf-8')
except Exception as e:
logger.info("could not convert argument to bytes :%s " % e)
return None
accounts = DBInterface(self._db, DBPrefix.ST_Account, AccountState)
acct = accounts.TryGet(keyval=address)
return acct
def GetStorageItem(self, storage_key):
storages = DBInterface(self._db, DBPrefix.ST_Storage, StorageItem)
item = storages.TryGet(storage_key.ToArray())
return item
def GetAssetState(self, assetId):
if type(assetId) is str:
try:
assetId = assetId.encode('utf-8')
except Exception as e:
logger.info("could not convert argument to bytes :%s " % e)
return None
assets = DBInterface(self._db, DBPrefix.ST_Asset, AssetState)
asset = assets.TryGet(assetId)
return asset
def ShowAllAssets(self):
res = []
with self._db.openIter(DBProperties(DBPrefix.ST_Asset, include_value=False)) as it:
for key in it:
res.append(key[1:]) # remove prefix byte
return res
def GetTransaction(self, hash):
if type(hash) is str:
hash = hash.encode('utf-8')
elif type(hash) is UInt256:
hash = hash.ToBytes()
out = self._db.get(DBPrefix.DATA_Transaction + hash)
if out is not None:
out = bytearray(out)
height = int.from_bytes(out[:4], 'little')
out = out[4:]
outhex = binascii.unhexlify(out)
return Transaction.DeserializeFromBufer(outhex, 0), height
return None, -1
def SearchContracts(self, query):
res = []
snapshot = self._db.createSnapshot()
keys = []
with self._db.openIter(DBProperties(DBPrefix.ST_Contract, include_value=False)) as it:
for key in it:
keys.append(key[1:]) # remove prefix byte
query = query.casefold()
for item in keys:
contract = snapshot.Contracts.TryGet(item)
try:
if query in contract.Name.decode('utf-8').casefold():
res.append(contract)
elif query in contract.Author.decode('utf-8').casefold():
res.append(contract)
elif query in contract.Description.decode('utf-8').casefold():
res.append(contract)
elif query in contract.Email.decode('utf-8').casefold():
res.append(contract)
except Exception as e:
logger.info("Could not query contract: %s " % e)
return res
def ShowAllContracts(self):
keys = []
with self._db.openIter(DBProperties(DBPrefix.ST_Contract, include_value=False)) as it:
for key in it:
keys.append(key[1:]) # remove prefix byte
return keys
def GetContract(self, hash):
if type(hash) is str:
try:
hash = UInt160.ParseString(hash).ToBytes()
except Exception as e:
logger.info("could not convert argument to bytes :%s " % e)
return None
contracts = DBInterface(self._db, DBPrefix.ST_Contract, ContractState)
contract = contracts.TryGet(keyval=hash)
return contract
def GetAllSpentCoins(self):
coins = DBInterface(self._db, DBPrefix.ST_SpentCoin, SpentCoinState)
return coins.Keys
def GetUnspent(self, hash, index):
coins = DBInterface(self._db, DBPrefix.ST_Coin, UnspentCoinState)
state = coins.TryGet(hash)
if state is None:
return None
if index >= len(state.Items):
return None
if state.Items[index] & CoinState.Spent > 0:
return None
tx, height = self.GetTransaction(hash)
return tx.outputs[index]
def GetSpentCoins(self, tx_hash):
if type(tx_hash) is not bytes:
tx_hash = bytes(tx_hash.encode('utf-8'))
coins = DBInterface(self._db, DBPrefix.ST_SpentCoin, SpentCoinState)
result = coins.TryGet(keyval=tx_hash)
return result
def GetAllUnspent(self, hash):
unspents = []
unspentcoins = DBInterface(self._db, DBPrefix.ST_Coin, UnspentCoinState)
state = unspentcoins.TryGet(keyval=hash.ToBytes())
if state:
tx, height = self.GetTransaction(hash)
for index, item in enumerate(state.Items):
if item & CoinState.Spent == 0:
unspents.append(tx.outputs[index])
return unspents
def GetUnclaimed(self, hash):
tx, height = self.GetTransaction(hash)
if tx is None:
return None
out = {}
coins = DBInterface(self._db, DBPrefix.ST_SpentCoin, SpentCoinState)
state = coins.TryGet(keyval=hash.ToBytes())
if state:
for item in state.Items:
out[item.index] = SpentCoin(tx.outputs[item.index], height, item.height)
return out
def SearchAssetState(self, query):
res = []
snapshot = self._db.createSnapshot()
keys = []
with self._db.openIter(DBProperties(DBPrefix.ST_Asset, include_value=False)) as it:
for key in it:
keys.append(key[1:]) # remove prefix byte
if query.lower() == "neo":
query = "AntShare"
if query.lower() in {"gas", "neogas"}:
query = "AntCoin"
for item in keys:
asset = snapshot.Assets.TryGet(item)
if query in asset.Name.decode('utf-8'):
res.append(asset)
elif query in Crypto.ToAddress(asset.Issuer):
res.append(asset)
elif query in Crypto.ToAddress(asset.Admin):
res.append(asset)
return res
def GetEnrollments(self):
# abstract
pass
@staticmethod
def GetConsensusAddress(validators):
"""
Get the script hash of the consensus node.
Args:
validators (list): of Ellipticcurve.ECPoint's
Returns:
UInt160:
"""
vlen = len(validators)
script = Contract.CreateMultiSigRedeemScript(vlen - int((vlen - 1) / 3), validators)
return Crypto.ToScriptHash(script)
def GetValidators(self, others):
# votes = Counter([len(vs.PublicKeys) for vs in self.GetVotes(others)]).items()
# TODO: Sorting here may cost a lot of memory, considering whether to use other mechanisms
# votes = GetVotes(others).OrderBy(p => p.PublicKeys.Length).ToArray()
# int validators_count = (int)votes.WeightedFilter(0.25, 0.75, p => p.Count.GetData(), (p, w) => new
# {
# ValidatorsCount = p.PublicKeys.Length,
# Weight = w
# }).WeightedAverage(p => p.ValidatorsCount, p => p.Weight)
# validators_count = Math.Max(validators_count, StandbyValidators.Length)
# Dictionary<ECPoint, Fixed8> validators = GetEnrollments().ToDictionary(p => p.PublicKey, p => Fixed8.Zero)
# foreach (var vote in votes)
# {
# foreach (ECPoint pubkey in vote.PublicKeys.Take(validators_count))
# {
# if (validators.ContainsKey(pubkey))
# validators[pubkey] += vote.Count
# }
# }
# return validators.OrderByDescending(p => p.Value).ThenBy(p => p.Key).Select(p => p.Key).Concat(StandbyValidators).Take(validators_count)
# }
raise NotImplementedError()
def GetNextBlockHash(self, hash):
if isinstance(hash, (UInt256, bytes)):
header = self.GetHeader(hash)
else:
# unclear why this branch exists
header = self.GetHeader(hash.ToBytes())
if header:
if header.Index + 1 >= len(self._header_index):
return None
return self._header_index[header.Index + 1]
return None
def GetScript(self, script_hash):
return self.GetContract(script_hash)
def GetSysFeeAmountByHeight(self, height):
"""
Get the system fee for the specified block.
Args:
height (int): block height.
Returns:
int:
"""
hash = self.GetBlockHash(height)
return self.GetSysFeeAmount(hash)
def OnPersistCompleted(self, block):
self.PersistCompleted.on_change(block)
msgrouter.on_block_persisted(block)
@property
def BlockCacheCount(self):
return len(self._block_cache)
def Pause(self):
self._paused = True
def Resume(self):
self._paused = False
async def Persist(self, block):
self._persisting_block = block
snapshot = self._db.createSnapshot()
snapshot.PersistingBlock = block
amount_sysfee = self.GetSysFeeAmount(block.PrevHash) + (block.TotalFees().value / Fixed8.D)
amount_sysfee_bytes = struct.pack("<d", amount_sysfee)
to_dispatch = []
with self._db.getBatch() as wb:
wb.put(DBPrefix.DATA_Block + block.Hash.ToBytes(), amount_sysfee_bytes + block.Trim())
for tx_idx, tx in enumerate(block.Transactions):
with self._db.getBatch() as tx_wb:
tx_wb.put(DBPrefix.DATA_Transaction + tx.Hash.ToBytes(), block.IndexBytes() + tx.ToArray())
# go through all outputs and add unspent coins to them
unspentcoinstate = UnspentCoinState.FromTXOutputsConfirmed(tx.outputs)
snapshot.UnspentCoins.Add(tx.Hash.ToBytes(), unspentcoinstate)
# go through all the accounts in the tx outputs
for output in tx.outputs:
account = snapshot.Accounts.GetAndChange(output.AddressBytes, lambda: AccountState(output.ScriptHash))
if account.HasBalance(output.AssetId):
account.AddToBalance(output.AssetId, output.Value)
else: