Skip to content
This repository was archived by the owner on Nov 15, 2021. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions neo/Core/Blockchain.py
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,9 @@ def GetAssetState(self, assetId):
def SearchAssetState(self, query):
pass

def ShowAllAssets(self):
pass

def GetHeaderHash(self, height):
pass

Expand Down
8 changes: 5 additions & 3 deletions neo/Core/FunctionCode.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from neocore.IO.Mixins import SerializableMixin
from neocore.Cryptography.Crypto import Crypto
from neocore.BigInteger import BigInteger
from neo.SmartContract.ContractParameterType import ContractParameterType
from neo.SmartContract.ContractParameterType import ContractParameterType, ToName


class FunctionCode(SerializableMixin):
Expand Down Expand Up @@ -104,9 +104,11 @@ def ToJson(self):
Returns:
dict:
"""
parameters = self.ParameterList.hex()
paramlist = [ToName(ContractParameterType.FromString(parameters[i:i + 2]).value) for i in range(0, len(parameters), 2)]
return {
'hash': self.ScriptHash().To0xString(),
'script': self.Script.hex(),
'parameters': self.ParameterList.hex(),
'returntype': self.ReturnType if type(self.ReturnType) is int else self.ReturnType.hex()
'parameters': paramlist,
'returntype': ToName(self.ReturnType) if type(self.ReturnType) is int else ToName(int(self.ReturnType))
}
12 changes: 7 additions & 5 deletions neo/Core/State/ContractState.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,19 +183,18 @@ def ToJson(self):
Returns:
dict:
"""
codejson = self.Code.ToJson()

name = 'Contract'

try:
name = self.Name.decode('utf-8')
except Exception as e:
pass

jsn = {
jsn = {'version': self.StateVersion}

jsn_code = self.Code.ToJson()

'version': self.StateVersion,
'code': codejson,
jsn_contract = {
'name': name,
'code_version': self.CodeVersion.decode('utf-8'),
'author': self.Author.decode('utf-8'),
Expand All @@ -208,6 +207,9 @@ def ToJson(self):
}
}

jsn.update(jsn_code)
jsn.update(jsn_contract)

if self._nep_token:
jsn['token'] = self._nep_token.ToJson()

Expand Down
4 changes: 2 additions & 2 deletions neo/Core/TX/test_transactions.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,8 @@ def test_publish_tx_deserialize(self):
self.assertEqual(contract['description'], 'Lock your assets until a timestamp.')

self.assertEqual(contract['code']['hash'], '0xffbd1a7ad1e2348b6b3822426f364bfb4bcce3b9')
self.assertEqual(contract['code']['returntype'], 1)
self.assertEqual(contract['code']['parameters'], '020500')
self.assertEqual(contract['code']['returntype'], "Boolean")
self.assertEqual(contract['code']['parameters'], ['Integer', 'ByteArray', 'Signature'])
self.assertEqual(Fixed8.FromDecimal(settings.ALL_FEES['PublishTransaction']), tx.SystemFee())

ir = b'd100644011111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111081234567890abcdef0415cd5b0769cc4ee2f1c9f4e0782756dabf246d0a4fe60a035400000000'
Expand Down
6 changes: 6 additions & 0 deletions neo/Implementations/Blockchains/LevelDB/LevelDBBlockchain.py
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,12 @@ def GetAssetState(self, assetId):

return asset

def ShowAllAssets(self):

assets = DBCollection(self._db, DBPrefix.ST_Asset, AssetState)
keys = assets.Keys
return keys

def GetTransaction(self, hash):

if type(hash) is str:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,7 @@ def test_GetHeaderBy(self):
invalid_bc_height = self._blockchain.Height + 1
block = self._blockchain.GetHeaderBy(invalid_bc_height)
self.assertEqual(block, None)

def test_ShowAllAssets(self):
assets = Blockchain.Default().ShowAllAssets()
self.assertEqual(len(assets), 2)
210 changes: 206 additions & 4 deletions neo/Prompt/Commands/Show.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from neo.Prompt.Utils import get_arg
from neo.Core.Blockchain import Blockchain
from neocore.UInt256 import UInt256
from neocore.UInt160 import UInt160
from neo.IO.MemoryStream import StreamManager
from neo.Network.NodeLeader import NodeLeader
from neo.Implementations.Notifications.LevelDB.NotificationDB import NotificationDB
Expand All @@ -25,6 +26,11 @@ def __init__(self):
self.register_sub_command(CommandShowTx())
self.register_sub_command(CommandShowMem())
self.register_sub_command(CommandShowNodes(), ['node'])
self.register_sub_command(CommandShowState())
self.register_sub_command(CommandShowNotifications())
self.register_sub_command(CommandShowAccount())
self.register_sub_command(CommandShowAsset())
self.register_sub_command(CommandShowContract())

def command_desc(self):
return CommandDesc('show', 'show useful data')
Expand Down Expand Up @@ -70,11 +76,11 @@ def execute(self, arguments):
print("Could not locate block %s" % item)
return
else:
print("please specify a block")
print("please specify a supported block attribute: index or scripthash")
return

def command_desc(self):
p1 = ParameterDesc('index/hash', 'the index or scripthash of the block')
p1 = ParameterDesc('attribute', 'the block index or scripthash')
p2 = ParameterDesc('tx', 'arg to only show block transactions', optional=True)
return CommandDesc('block', 'show a specified block', [p1, p2])

Expand All @@ -94,11 +100,11 @@ def execute(self, arguments):
print("Could not locate header %s\n" % item)
return
else:
print("Please specify a header")
print("Please specify a supported header attribute: index or scripthash")
return

def command_desc(self):
p1 = ParameterDesc('index/hash', 'the index or scripthash of the block header')
p1 = ParameterDesc('attribute', 'the header index or scripthash')
return CommandDesc('header', 'show the header of a specified block', [p1])


Expand Down Expand Up @@ -167,3 +173,199 @@ def execute(self, arguments=None):

def command_desc(self):
return CommandDesc('nodes', 'show connected peers')


class CommandShowState(CommandBase):
def __init__(self):
super().__init__()

def execute(self, arguments=None):
height = Blockchain.Default().Height
headers = Blockchain.Default().HeaderHeight

diff = height - PromptData.Prompt.start_height
now = datetime.datetime.utcnow()
difftime = now - PromptData.Prompt.start_dt

mins = difftime / datetime.timedelta(minutes=1)
secs = mins * 60

bpm = 0
tps = 0
if diff > 0 and mins > 0:
bpm = diff / mins
tps = Blockchain.Default().TXProcessed / secs

out = "Progress: %s / %s\n" % (height, headers)
out += "Block-cache length %s\n" % Blockchain.Default().BlockCacheCount
out += "Blocks since program start %s\n" % diff
out += "Time elapsed %s mins\n" % mins
out += "Blocks per min %s \n" % bpm
out += "TPS: %s \n" % tps
print(out)
return out

def command_desc(self):
return CommandDesc('state', 'show the status of the node')


class CommandShowNotifications(CommandBase):
def __init__(self):
super().__init__()

def execute(self, arguments):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

neo> show notifications -1
Could not parse block height can't convert negative int to unsigned

neo> show notifications bla
Could not parse block height invalid literal for int() with base 10: 'bla'

neo> show notifications
Could not execute command: object of type 'NoneType' has no len()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 884, in _bootstrap
    self._bootstrap_inner()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 916, in _bootstrap_inner
    self.run()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/
and then some

unfriendly error message for an invalid arguments

similar errors are also present for show contract 234 and show asset 234. I stopped reviewing at this point. Please do some manual testing, as these can be captured before PR'ing. Thanks!

if NotificationDB.instance() is None:
print("No notification DB Configured")
return

item = get_arg(arguments)
if item is not None:
if item[0:2] == "0x":
item = item[2:]

events = []

if len(item) == 34 and item[0] == 'A':
events = NotificationDB.instance().get_by_addr(item)

elif len(item) == 40:
events = NotificationDB.instance().get_by_contract(item)

else:
try:
block_height = int(item)
if block_height < Blockchain.Default().Height:
events = NotificationDB.instance().get_by_block(block_height)
else:
print("Block %s not found" % block_height)
return
except Exception:
print("Could not find notifications from args: %s" % arguments)
return

if len(events):
[print(json.dumps(e.ToJson(), indent=4)) for e in events]
return events
else:
print("No events found for %s" % item)
return
else:
print("Please specify a supported attribute: a block index, an address, or contract scripthash")
return

def command_desc(self):
p1 = ParameterDesc('attribute', 'the block index, an address, or contract scripthash to show notifications for')
return CommandDesc('notifications', 'show specified contract execution notifications', [p1])


class CommandShowAccount(CommandBase):
def __init__(self):
super().__init__()

def execute(self, arguments):
item = get_arg(arguments)
if item is not None:
account = Blockchain.Default().GetAccountState(item, print_all_accounts=True)

if account is not None:
print(json.dumps(account.ToJson(), indent=4))
return account.ToJson()
else:
print("Account %s not found" % item)
return
else:
print("Please specify an account address")
return

def command_desc(self):
p1 = ParameterDesc('address', 'the address to show')
return CommandDesc('account', 'show the assets (NEO/GAS) held by a specified address', [p1])


class CommandShowAsset(CommandBase):
def __init__(self):
super().__init__()

def execute(self, arguments):
item = get_arg(arguments)
if item is not None:
if item.lower() == "all":
assets = Blockchain.Default().ShowAllAssets()
assetlist = []
for asset in assets:
state = Blockchain.Default().GetAssetState(asset.decode('utf-8')).ToJson()
asset_dict = {state['name']: state['assetId']}
assetlist.append(asset_dict)
print(json.dumps(assetlist, indent=4))
return assetlist

if item.lower() == 'neo':
assetId = Blockchain.Default().SystemShare().Hash
elif item.lower() == 'gas':
assetId = Blockchain.Default().SystemCoin().Hash
else:
try:
assetId = UInt256.ParseString(item)
except Exception:
print("Could not find asset from args: %s" % arguments)
return

asset = Blockchain.Default().GetAssetState(assetId.ToBytes())

if asset is not None:
print(json.dumps(asset.ToJson(), indent=4))
return asset.ToJson()
else:
print("Asset %s not found" % item)
return
else:
print('Please specify a supported attribute: asset name, assetId, or "all" shows all assets')
return

def command_desc(self):
p1 = ParameterDesc('attribute', 'the asset name, assetId, or "all" shows all assets\n\n'
f"{' ':>17} Example:\n"
f"{' ':>20} 'neo' or 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b'\n"
f"{' ':>20} 'gas' or '602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7'\n")
return CommandDesc('asset', 'show a specified asset', [p1])


class CommandShowContract(CommandBase):
def __init__(self):
super().__init__()

def execute(self, arguments):
item = get_arg(arguments)
if item is not None:
if item.lower() == "all":
contracts = Blockchain.Default().ShowAllContracts()
contractlist = []
for contract in contracts:
state = Blockchain.Default().GetContract(contract.decode('utf-8')).ToJson()
contract_dict = {state['name']: state['hash']}
contractlist.append(contract_dict)
print(json.dumps(contractlist, indent=4))
return contractlist

try:
hash = UInt160.ParseString(item).ToBytes()
except Exception:
print("Could not find contract from args: %s" % arguments)
return

contract = Blockchain.Default().GetContract(hash)

if contract is not None:
contract.DetermineIsNEP5()
print(json.dumps(contract.ToJson(), indent=4))
return contract.ToJson()
else:
print("Contract %s not found" % item)
return
else:
print('Please specify a supported attribute: contract scripthash or "all"')
return

def command_desc(self):
p1 = ParameterDesc('attribute', 'the contract scripthash, or "all" shows all contracts')
return CommandDesc('contract', 'show a specified smart contract', [p1])
Loading