Skip to content
This repository has been archived by the owner on Nov 15, 2021. It is now read-only.

Commit

Permalink
fix tests, merge from development
Browse files Browse the repository at this point in the history
  • Loading branch information
localhuman committed Feb 15, 2018
2 parents d9bf5a1 + ef170b0 commit 805fea9
Show file tree
Hide file tree
Showing 8 changed files with 78 additions and 50 deletions.
6 changes: 4 additions & 2 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
Changelog
=========

All notable changes to this project following the ``0.4.0`` release will be documented in this file.
All notable changes to this project are documented in this file.

[0.4.7] 2018-02-13
[0.4.7-dev] work in progress
----------------------------

- Fix Gas Cost Calculation (`PR #220 <https://github.com/CityOfZion/neo-python/pull/220>`_)
- Clarify message for token mint command (`PR #212 <https://github.com/CityOfZion/neo-python/pull/212>`_)
- Troubleshooting osx script (`PR #208 <https://github.com/CityOfZion/neo-python/pull/208>`_)
- Make Contract Search case insensitive (`PR #207 <https://github.com/CityOfZion/neo-python/pull/207>`_)
- implement a more robust CLI command parser


[0.4.6] 2018-01-24
------------------

Expand Down
17 changes: 4 additions & 13 deletions examples/json-rpc-api-server.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
#!/usr/bin/env python
#!/usr/bin/env python3
"""
This example provides a JSON-RPC API to query blockchain data, implementing `neo.api.JSONRPC.JsonRpcApi`
"""

import argparse
import os

import logzero
from logzero import logger
from twisted.internet import reactor, task

from neo import __version__
Expand All @@ -19,14 +19,11 @@
from neo.UserPreferences import preferences

# Logfile settings & setup
LOGFILE_FN = os.path.join(DIR_PROJECT_ROOT, 'notifications.log')
LOGFILE_FN = os.path.join(DIR_PROJECT_ROOT, 'json-rpc.log')
LOGFILE_MAX_BYTES = 5e7 # 50 MB
LOGFILE_BACKUP_COUNT = 3 # 3 logfiles history
settings.set_logfile(LOGFILE_FN, LOGFILE_MAX_BYTES, LOGFILE_BACKUP_COUNT)

# Prompt history filename
FILENAME_PROMPT_HISTORY = os.path.join(DIR_PROJECT_ROOT, '.prompt.py.history')


def main():
parser = argparse.ArgumentParser()
Expand All @@ -35,9 +32,6 @@ def main():
parser.add_argument("-p", "--privnet", action="store_true", default=False,
help="Use PrivNet instead of the default TestNet")
parser.add_argument("-c", "--config", action="store", help="Use a specific config file")
parser.add_argument("-t", "--set-default-theme", dest="theme",
choices=["dark", "light"],
help="Set the default theme to be loaded from the config file. Default: 'dark'")
parser.add_argument('--version', action='version',
version='neo-python v{version}'.format(version=__version__))

Expand All @@ -58,9 +52,6 @@ def main():
elif args.privnet:
settings.setup_privnet()

if args.theme:
preferences.set_theme(args.theme)

# Instantiate the blockchain and subscribe to notifications
blockchain = LevelDBBlockchain(settings.LEVELDB_PATH)
Blockchain.RegisterBlockchain(blockchain)
Expand All @@ -78,7 +69,7 @@ def main():

host = "0.0.0.0"
port = settings.RPC_PORT
print("Starting json-rpc api server on http://%s:%s" % (host, port))
logger.info("Starting json-rpc api server on http://%s:%s" % (host, port))

api_server = JsonRpcApi(port)
api_server.app.run(host, port)
Expand Down
16 changes: 7 additions & 9 deletions examples/notification-rest-api-server.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
#!/usr/bin/env python
#!/usr/bin/env python3
"""
This example provides a REST API to query notifications from the blockchain, implementing `neo.api.RESTAPI.NotificationRestApi`
See it live here: http://notifications.neeeo.org/
"""

import argparse
import os

import logzero
from logzero import logger
from twisted.internet import reactor, task

from neo import __version__
Expand All @@ -32,9 +34,6 @@ def main():
parser.add_argument("-p", "--privnet", action="store_true", default=False,
help="Use PrivNet instead of the default TestNet")
parser.add_argument("-c", "--config", action="store", help="Use a specific config file")
parser.add_argument("-t", "--set-default-theme", dest="theme",
choices=["dark", "light"],
help="Set the default theme to be loaded from the config file. Default: 'dark'")
parser.add_argument('--version', action='version',
version='neo-python v{version}'.format(version=__version__))

Expand All @@ -55,9 +54,6 @@ def main():
elif args.privnet:
settings.setup_privnet()

if args.theme:
preferences.set_theme(args.theme)

# Instantiate the blockchain and subscribe to notifications
blockchain = LevelDBBlockchain(settings.LEVELDB_PATH)
Blockchain.RegisterBlockchain(blockchain)
Expand All @@ -73,7 +69,9 @@ def main():
reactor.suggestThreadPoolSize(15)
NodeLeader.Instance().Start()

notif_server.app.run('0.0.0.0', 8000)
port = 8000
logger.info("Starting notification-api server on port %s" % (port))
notif_server.app.run('0.0.0.0', port)


if __name__ == "__main__":
Expand Down
19 changes: 19 additions & 0 deletions neo/Implementations/Wallets/peewee/test_user_wallet.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
from neocore.Fixed8 import Fixed8
from neocore.KeyPair import KeyPair
from neo.Wallets.NEP5Token import NEP5Token
from neo.SmartContract.ContractParameterContext import ContractParametersContext
from neo.Core.TX.Transaction import ContractTransaction, TransactionOutput
from neo.Network.NodeLeader import NodeLeader
import json
import binascii

Expand Down Expand Up @@ -171,3 +174,19 @@ def test_8_named_addr(self):
self.assertIsInstance(presult, bytearray)

self.assertEqual(presult, self.wallet_1_script_hash.Data)

def test_9_send_neo_tx(self):

wallet = self.GetWallet1()

tx = ContractTransaction()
tx.outputs = [TransactionOutput(Blockchain.SystemShare().Hash, Fixed8.FromDecimal(10.0), self.import_watch_addr)]

tx = wallet.MakeTransaction(tx)

cpc = ContractParametersContext(tx)
wallet.Sign(cpc)
tx.scripts = cpc.GetScripts()

result = NodeLeader.Instance().Relay(tx)
self.assertEqual(result, True)
1 change: 1 addition & 0 deletions neo/SmartContract/ApplicationEngine.py
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,7 @@ def Run(script, container=None):
Returns:
ApplicationEngine
"""

from neo.Core.Blockchain import Blockchain
from neo.SmartContract.StateMachine import StateMachine
from neo.EventHub import events
Expand Down
43 changes: 20 additions & 23 deletions neo/api/JSONRPC/JsonRpcApi.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,9 @@
from neo.Core.Blockchain import Blockchain
from neo.api.utils import json_response
from neo.Core.State.AccountState import AccountState
from neo.Core.State.ContractState import ContractState
from neo.Core.TX.Transaction import Transaction
from neocore.UInt160 import UInt160
from neocore.UInt256 import UInt256
from neo.Wallets import Wallet
from neo.Core.Helper import Helper
from neo.Network.NodeLeader import NodeLeader
import binascii
Expand Down Expand Up @@ -119,26 +118,6 @@ def home(self, request):
error = JsonRpcError.internalError(str(e))
return self.get_custom_error_payload(request_id, error.code, error.message)

def parse_uint_str(self, param):
if param[0:2] == '0x':
return param[2:]
return param

def validateaddress(self, params):
# check for [] parameter or [""]
if not params or params[0] == '':
raise JsonRpcError(-100, "Missing argument")

isValid = False
try:
data = base58.b58decode_check(params[0])
if len(data) == 21 and data[0] == settings.ADDRESS_VERSION:
isValid = True
except Exception as e:
pass

return {"address": params[0], "isvalid": isValid}

def json_rpc_method_handler(self, method, params):

if method == "getaccountstate":
Expand Down Expand Up @@ -250,7 +229,10 @@ def json_rpc_method_handler(self, method, params):
return self.get_invoke_result(script)

elif method == "sendrawtransaction":
raise NotImplementedError()
tx_script = binascii.unhexlify(params[0].encode('utf-8'))
transaction = Transaction.DeserializeFromBufer(tx_script)
result = NodeLeader.Instance().Relay(transaction)
return result

elif method == "submitblock":
raise NotImplementedError()
Expand Down Expand Up @@ -309,3 +291,18 @@ def get_invoke_result(self, script):
"gas_consumed": appengine.GasConsumed().ToString(),
"stack": [ContractParameter.ToParameter(item).ToJson() for item in appengine.EvaluationStack.Items]
}

def validateaddress(self, params):
# check for [] parameter or [""]
if not params or params[0] == '':
raise JsonRpcError(-100, "Missing argument")

isValid = False
try:
data = base58.b58decode_check(params[0])
if len(data) == 21 and data[0] == settings.ADDRESS_VERSION:
isValid = True
except Exception as e:
pass

return {"address": params[0], "isvalid": isValid}
22 changes: 22 additions & 0 deletions neo/api/JSONRPC/test_json_rpc_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -413,3 +413,25 @@ def test_gettxout(self):
expected_value = "2609.997813"
self.assertEqual(output_index, res["result"]["n"])
self.assertEqual(expected_value, res["result"]["value"])

def test_send_raw_tx(self):
raw_tx = '80000001b10ad9ec660bf343c0eb411f9e05b4fa4ad8abed31d4e4dc5bb6ae416af0c4de000002e72d286979ee6cb1b7e65dfddfb2e384100b8d148e7758de42e4168b71792c60c8db571300000000af12a8687b14948bc4a008128a550a63695bc1a5e72d286979ee6cb1b7e65dfddfb2e384100b8d148e7758de42e4168b71792c603808b44002000000eca8fcf94e7a2a7fc3fd54ae0ed3d34d52ec25900141404749ce868ed9588f604eeeb5c523db39fd57cd7f61d04393a1754c2d32f131d67e6b1ec561ac05012b7298eb5ff254487c76de0b2a0c4d097d17cec708c0a9802321025b5c8cdcb32f8e278e111a0bf58ebb463988024bb4e250aa4310b40252030b60ac'
req = self._gen_rpc_req("sendrawtransaction", params=[raw_tx])
mock_req = mock_request(json.dumps(req).encode("utf-8"))
res = json.loads(self.app.home(mock_req))
self.assertEqual(res['result'], True)

def test_send_raw_tx_bad(self):
raw_tx = '80000001b10ad9ec660bf343c0eb411f9e05b4fa4ad8abed31d4e4dc5bb6ae416af0c4de000002e72d286979ee6cb1b7e65dfddfb2e384100b8d148e7758de42e4168b71792c60c8db571300000000af12a8687b14948bc4a008128a550a63695bc1a5e72d286979ee6cb1b7e65dfddfb2e384100b8d148e7758de42e4168b71792c603808b44002000000eca8fcf94e7a2a7fc3fd54ae0ed3d34d52ec25900141404749ce868ed9588f604eeeb5c523db39fd57cd7f61d04393a1754c2d32f131d67e6b1ec561ac05012b7298eb5ff254487c76de0b2a0c4d097d17cec708c0a9802321025b5c8cdcb32f8e278e111a0bf58ebb463988024bb4e250aa4310b40252030b60ac'
req = self._gen_rpc_req("sendrawtransaction", params=[raw_tx])
mock_req = mock_request(json.dumps(req).encode("utf-8"))
res = json.loads(self.app.home(mock_req))
self.assertEqual(res['result'], False)

def test_send_raw_tx_bad_2(self):
raw_tx = '80000001b10ad9ec660bf343c0eb411f9e05b4fa4ad8abed31d4e4dc5bb6ae416af0c4de000002e72d286979ee6cbb7e65dfddfb2e384100b8d148e7758de42e4168b71792c60c8db571300000000af12a8687b14948bc4a008128a550a63695bc1a5e72d286979ee6cb1b7e65dfddfb2e384100b8d148e7758de42e4168b71792c603808b44002000000eca8fcf94e7a2a7fc3fd54ae0ed3d34d52ec25900141404749ce868ed9588f604eeeb5c523db39fd57cd7f61d04393a1754c2d32f131d67e6b1ec561ac05012b7298eb5ff254487c76de0b2a0c4d097d17cec708c0a9802321025b5c8cdcb32f8e278e111a0bf58ebb463988024bb4e250aa4310b40252030b60ac'
req = self._gen_rpc_req("sendrawtransaction", params=[raw_tx])
mock_req = mock_request(json.dumps(req).encode("utf-8"))
res = json.loads(self.app.home(mock_req))
self.assertTrue('error' in res)
self.assertEqual(res['error']['code'], -32603)
4 changes: 1 addition & 3 deletions neo/api/REST/test_notification_rest_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

class NotificationDBTestCase(BlockchainFixtureTestCase):

N_FIXTURE_REMOTE_LOC = 'https://s3.us-east-2.amazonaws.com/cityofzion/fixtures/notif_fixture.tar.gz'
N_FIXTURE_REMOTE_LOC = 'https://s3.us-east-2.amazonaws.com/cityofzion/fixtures/notif_fixture_v3.tar.gz'
N_FIXTURE_FILENAME = './Chains/notif_fixture_v3.tar.gz'
N_NOTIFICATION_DB_NAME = 'fixtures/test_notifications'

Expand Down Expand Up @@ -135,8 +135,6 @@ def test_8_bad_addr(self):
self.assertIsInstance(results, list)
self.assertIn('Could not get notifications', jsn['message'])

# this following test doesn't work because we'd have to load in the blockchain that matches these notifications

def test_9_by_tx(self):
mock_req = requestMock(path=b'/tx/0x4c927a7f365cb842ea3576eae474a89183c9e43970a8509b23570a86cb4f5121')
res = self.app.get_by_tx(mock_req, '0x4c927a7f365cb842ea3576eae474a89183c9e43970a8509b23570a86cb4f5121')
Expand Down

0 comments on commit 805fea9

Please sign in to comment.