Skip to content
This repository has been archived by the owner on Aug 8, 2018. It is now read-only.

Commit

Permalink
Fixed the Filter not found error code
Browse files Browse the repository at this point in the history
  • Loading branch information
RomanZacharia committed Aug 12, 2016
1 parent 3fc0af6 commit 609d08e
Show file tree
Hide file tree
Showing 2 changed files with 172 additions and 41 deletions.
75 changes: 49 additions & 26 deletions pyethapp/jsonrpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,16 @@ class JSONRPCExecutionError(FixedErrorMessageMixin, ExecutionError):
message = 'Execution error'


class NotExistError(JSONRPCExecutionError):
edata = [
{
'code': 100,
'message': 'The item does not exist'
}
]

def __init__(self, message):
self.edata[0]['message'] = message

class InsufficientGasError(JSONRPCExecutionError):
edata = [
Expand All @@ -88,8 +98,6 @@ class RejectedError(JSONRPCExecutionError):
{
'code': 104,
'message': 'Rejected: Inappropriate value'
# The 'reason' data field might be excessive
# 'reason': 'Inappropriate value'
}
]

Expand Down Expand Up @@ -470,8 +478,10 @@ def quantity_encoder(i):
return '0x' + (encode_hex(data).lstrip('0') or '0')


def data_decoder(data):
def data_decoder(data, name=None):
"""Decode `data` representing unformatted data."""
if type(data) is dict and name:
data = data[name]
if not data.startswith('0x'):
data = '0x' + data
if len(data) % 2 != 0:
Expand All @@ -482,6 +492,8 @@ def data_decoder(data):
try:
return decode_hex(data[2:])
except TypeError:
if name:
raise RejectedError('Invalid ' + name + ' data hex encoding')
raise BadRequestError('Invalid data hex encoding', data[2:])


Expand All @@ -498,10 +510,12 @@ def data_encoder(data, length=None):
return '0x' + s.rjust(length * 2, '0')


def address_decoder(data):
def address_decoder(data, name=None):
"""Decode an address from hex with 0x prefix to 20 bytes."""
addr = data_decoder(data)
addr = data_decoder(data, name)
if len(addr) not in (20, 0):
if name:
raise RejectedError(name + ' address must be 20 or 0 bytes long')
raise BadRequestError('Addresses must be 20 or 0 bytes long')
return addr

Expand Down Expand Up @@ -1173,7 +1187,7 @@ def sendTransaction(self, data):

def get_data_default(key, decoder, default=None):
if key in data:
return decoder(data[key])
return decoder(data, key)
return default

to = get_data_default('to', address_decoder, b'')
Expand All @@ -1198,13 +1212,19 @@ def get_data_default(key, decoder, default=None):
if nonce is None or nonce == 0:
nonce = self.app.services.chain.chain.head_candidate.get_nonce(sender)

tx = Transaction(nonce, gasprice, startgas, to, value, data_, v, r, s)
tx._sender = None
if not signed:
assert sender in self.app.services.accounts, 'can not sign: no account for sender'
self.app.services.accounts.sign_tx(sender, tx)
self.app.services.chain.add_transaction(tx, origin=None, force_broadcast=True)
log.debug('decoded tx', tx=tx.log_dict())
try:
tx = Transaction(nonce, gasprice, startgas, to, value, data_, v, r, s)
tx._sender = None
if not signed:
assert sender in self.app.services.accounts, 'can not sign: no account for sender'
self.app.services.accounts.sign_tx(sender, tx)
self.app.services.chain.add_transaction(tx, origin=None, force_broadcast=True)
log.debug('decoded tx', tx=tx.log_dict())
except InvalidTransaction as e:
if 'Startgas too low' in e.message:
raise InsufficientGasError()
raise

return data_encoder(tx.hash)

@public
Expand Down Expand Up @@ -1278,27 +1298,29 @@ def call(self, data, block_id='pending'):
except KeyError:
value = 0
try:
data_ = data_decoder(data['data'])
data_ = data_decoder(data, 'data')
except KeyError:
data_ = b''
try:
sender = address_decoder(data['from'])
sender = address_decoder(data, 'from')
except KeyError:
sender = '\x00' * 20

# apply transaction
nonce = test_block.get_nonce(sender)
tx = Transaction(nonce, gasprice, startgas, to, value, data_)
tx.sender = sender

try:
# apply transaction
nonce = test_block.get_nonce(sender)
tx = Transaction(nonce, gasprice, startgas, to, value, data_)
tx.sender = sender
errmsg = 'Invalid transaction'
success, output = processblock.apply_transaction(test_block, tx)
except processblock.InsufficientBalance as e:
except processblock.InsufficientBalance:
raise InsufficientGasError()
except InvalidTransaction as e:
if 'Startgas too low' in e.message:
raise InsufficientGasError()
success = False
errmsg = e.__class__.__name__ + e.message

# make sure we didn't change the real state
snapshot_after = block.snapshot()
assert snapshot_after == snapshot_before
Expand Down Expand Up @@ -1361,12 +1383,13 @@ def estimateGas(self, data, block_id='pending'):

# apply transaction
nonce = test_block.get_nonce(sender)
tx = Transaction(nonce, gasprice, startgas, to, value, data_)
tx.sender = sender

try:
tx = Transaction(nonce, gasprice, startgas, to, value, data_)
tx.sender = sender
success, output = processblock.apply_transaction(test_block, tx)
except processblock.InvalidTransaction:
except processblock.InvalidTransaction as e:
if 'Startgas too low' in e.message:
raise InsufficientGasError()
success = False
# make sure we didn't change the real state
snapshot_after = block.snapshot()
Expand Down Expand Up @@ -1644,7 +1667,7 @@ def uninstallFilter(self, id_):
@decode_arg('id_', quantity_decoder)
def getFilterChanges(self, id_):
if id_ not in self.filters:
raise BadRequestError('Unknown filter')
raise NotExistError('Unknown filter')
filter_ = self.filters[id_]
logger.debug('filter found', filter=filter_)
if isinstance(filter_, (BlockFilter, PendingTransactionFilter)):
Expand Down
138 changes: 123 additions & 15 deletions pyethapp/tests/test_jsonrpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,19 +240,7 @@ def test_rpc_errors(test_app):
assert chain.head_candidate.get_balance('\xff' * 20) == 0
sender = test_app.services.accounts.unlocked_accounts[0].address
assert chain.head_candidate.get_balance(sender) > 0
tx = {
'from': address_encoder(sender),
'to': address_encoder('\xff' * 20),
'value': quantity_encoder(1)
}
# res = data_decoder(test_app.rpc_request('eth_call', tx, 0x1))

# tr = type(res)

import pdb; pdb.set_trace()

# json01 = '{"id":4,"jsonrpc":"2.0","method":"eth_call","params":[{"to":"0x6295ee1b4f6dd65047762f924ecd367c17eabf8f","data":"0x12a7b914"},"0x8"]}'
# json01 = '{"id":4,"jsonrpc":"2.0","method":"eth_sendTransaction","params":['+json.dumps(tx)+']}'
reqid += 1
json02 = {
"id": reqid,
Expand All @@ -263,18 +251,138 @@ def test_rpc_errors(test_app):
{
'from': address_encoder(sender),
'to': address_encoder('\xff' * 20),
'gasPrice': '0x999999999999999999999999999999999999999999',
'gas': '0x1',
'gasPrice': '0x7777',
'value': quantity_encoder(100),
'data': '12345'
}
]
}
response = test_app.dispatch(json.dumps(json02))
assert response['error']['code'] == 3
assert response['error']['data'][0]['code'] == 102

reqid += 1
json03 = {
"id": reqid,
"jsonrpc": "2.0",
"method": "eth_call",
"params":
[
{
'from': address_encoder(sender),
'to': address_encoder('\xff' * 20),
'gasPrice': '0x01',
'value': quantity_encoder(100),
}
]
}
response = test_app.dispatch(json.dumps(json03))

assert response['error']['code'] == 3
assert response['error']['data'][0]['code'] == 104
# res = data_decoder(test_app.rpc_request('eth_getTransactionByHash', 0x1))

reqid += 1
json04 = {
"id": reqid,
"jsonrpc": "2.0",
"method": "eth_call",
"params":
[
{
'from': address_encoder(sender),
'to': address_encoder('\xff' * 20),
'gas': '0x1',
'gasPrice': '0x0',
'value': quantity_encoder(10000000),
}
]
}
response = test_app.dispatch(json.dumps(json04))
assert response['error']['code'] == 3
assert response['error']['data'][0]['code'] == 102

reqid += 1
json05 = {
"id": reqid,
"jsonrpc": "2.0",
"method": "eth_call",
"params":
[
{
'from': address_encoder(sender),
'to': address_encoder('\xff' * 20),
'gasPrice': '0x0',
'value': quantity_encoder(10000000),
}
]
}
response = test_app.dispatch(json.dumps(json05))
assert 'result' in response.keys()

reqid += 1
json06 = {
"id": reqid,
"jsonrpc": "2.0",
"method": "eth_sendTransaction",
"params":
[
{
'from': address_encoder(sender),
'to': address_encoder('\xff' * 20),
'value': quantity_encoder(1),
}
]
}
response = test_app.dispatch(json.dumps(json06))
assert 'result' in response.keys()

reqid += 1
json07 = {
"id": reqid,
"jsonrpc": "2.0",
"method": "eth_sendTransaction",
"params":
[
{
'from': address_encoder(sender),
'to': address_encoder('\xff' * 20),
'gas': '0x300000',
'gasPrice': '0x0',
'value': quantity_encoder(1),
}
]
}
response = test_app.dispatch(json.dumps(json07))
assert 'result' in response.keys()

reqid += 1
json08 = {
"id": reqid,
"jsonrpc": "2.0",
"method": "eth_getBlockByNumber",
"params":
[
"earliest",
False
]
}
response = test_app.dispatch(json.dumps(json08))
assert 'result' in response.keys()

reqid += 1
json09 = {
"id": reqid,
"jsonrpc": "2.0",
"method": "eth_getFilterChanges",
"params":
[
"0x12345" # invald filter id
]
}

response = test_app.dispatch(json.dumps(json09))
assert response['error']['code'] == 3
assert response['error']['data'][0]['code'] == 100


def test_send_transaction(test_app):
Expand Down

0 comments on commit 609d08e

Please sign in to comment.