Compare commits

...

201 Commits
main ... v1.0.2

Author SHA1 Message Date
Marek Kotewicz
70389b2888 Merge pull request #922 from ethcore/beta-staging
Master to beta v1.0.2
2016-04-11 16:42:09 +02:00
debris
8f63f6d32a fixed transaction deadlock 2016-04-11 14:39:01 +02:00
debris
f02f99cd3f fixed eth_getLogs 2016-04-11 14:38:18 +02:00
Gav Wood
bbbd6f01fc --unlock is comma-delimited. 2016-04-11 14:37:10 +02:00
debris
ddbce9f014 removed empty lines 2016-04-11 14:36:27 +02:00
debris
423c5e87da fixed eth_getLogs 2016-04-11 14:36:16 +02:00
NikVolf
a15d2882d0 removing lower-level defaults 2016-04-11 14:36:02 +02:00
NikVolf
6d5809757f create provided custom dir for keys if none 2016-04-11 14:35:55 +02:00
Gav Wood
e179b0e0c2 Merge pull request #908 from ethcore/beta-staging
Master to beta 1.0.2
2016-04-09 10:18:41 -07:00
arkpar
37eb0fb04e Use new json RPC server 2016-04-09 13:31:34 +02:00
Tomasz Drwięga
32b0a80a18 Removing Option from setup_rpc_server method return type 2016-04-09 13:29:13 +02:00
Tomasz Drwięga
9df9937922 Fixing compilation with rpc feature disabled 2016-04-09 13:29:06 +02:00
debris
eae66568a9 fixed #895 2016-04-09 13:28:55 +02:00
Tomasz Drwięga
ece348d173 Avoid signalling readiness when app is about to be closed 2016-04-09 13:28:43 +02:00
arkpar
cc0c54a45c Propagate transaction queue 2016-04-09 13:28:37 +02:00
Tomasz Drwięga
3f139116b2 Reverting order of shutdown event 2016-04-09 13:26:14 +02:00
Tomasz Drwięga
771e3998a9 Updating rpc comments 2016-04-09 13:26:08 +02:00
Tomasz Drwięga
03fbde9723 More descriptive message when closing 2016-04-09 13:26:00 +02:00
Tomasz Drwięga
3303aa73ff Tracing shutdown and changed order of IoManager shutdown process 2016-04-09 13:25:54 +02:00
Tomasz Drwięga
8367be6992 Rewriting messages 2016-04-09 13:25:46 +02:00
Tomasz Drwięga
e6237ed05e Removing additional thread from JSON-RPC 2016-04-09 13:25:39 +02:00
Tomasz Drwięga
0abdcedc03 Additional logging and error messages 2016-04-09 13:25:28 +02:00
Tomasz Drwięga
59a735e2c4 Removing match on constant 2016-04-09 13:25:20 +02:00
arkpar
bf24355480 Fixed eth_call nonce and gas handling 2016-04-09 13:25:16 +02:00
NikVolf
4ed15931af replacing /home/nikky also 2016-04-09 13:21:18 +02:00
NikVolf
c5553c1f21 passing key path to all invocations 2016-04-09 13:19:09 +02:00
debris
33d633eed1 fixed #875 and added tests for eth_sendTransaction 2016-04-09 13:16:40 +02:00
Nikolay Volf
a3a0de096d replace add with or 2016-04-09 13:10:20 +02:00
Tomasz Drwięga
aed708ffd8 More descriptive expectations to transaction queue consistency. 2016-04-09 13:09:55 +02:00
Tomasz Drwięga
66d3d7ec11 Fixing typo in bigint 2016-04-09 13:09:45 +02:00
Nikolay Volf
8503aeb2df [ci skip] update misleading cli help msg for author 2016-04-09 13:09:06 +02:00
arkpar
a7ebc1dd25 Handle geth keys with lowercase crypto key 2016-04-09 13:08:52 +02:00
Robert Habermeier
584d89f964 Find geth data store cross-platform.
Fixes #869
2016-04-09 13:08:40 +02:00
arkpar
4aeaab3a2f Fixed bootnode URL and error message 2016-04-09 13:08:03 +02:00
NikVolf
9750a31336 replace popcnt with mov 2016-04-09 13:07:48 +02:00
debris
404005cc93 fixed #855 2016-04-09 13:06:51 +02:00
Gav Wood
9b5bd37dc5 Merge pull request #905 from ethcore/sync-beta
Imporved sync error handling
2016-04-08 17:43:42 -07:00
arkpar
f96e5bc0d5 v1.0.2 2016-04-06 16:15:36 +02:00
arkpar
444c9c4375 Track import errors and restart sync 2016-04-06 16:15:31 +02:00
Gav Wood
2a2c24855c Fix build. 2016-03-28 21:19:28 +02:00
Gav Wood
712302391c Use sensible gas price. 2016-03-28 20:42:23 +02:00
Gav Wood
3023d76a46 Publish locally-made transactions to peers. 2016-03-28 19:43:49 +02:00
Gav Wood
f60d74b231 Merge pull request #844 from ethcore/sync-beta
Full sync restart on bad block
2016-03-28 15:49:39 +02:00
arkpar
3e192ab486 Full restart on bad block 2016-03-28 13:05:59 +02:00
Gav Wood
fe313677b3 Merge pull request #845 from ethcore/beta-staging
Merge fixes from master to beta
2016-03-28 10:00:50 +02:00
arkpar
20f3f356e5 v1.0.1 2016-03-28 02:25:12 +02:00
NikVolf
b9141b830b test for pending 2016-03-28 02:19:29 +02:00
NikVolf
a938385692 checking tx queue 2016-03-28 02:19:19 +02:00
debris
c9ac0392d8 tests for deserialization of issue #835 2016-03-28 02:18:50 +02:00
NikVolf
02dfc8632e fix test 2016-03-28 02:17:32 +02:00
NikVolf
ac2a62707a in cli call 2016-03-28 02:17:28 +02:00
NikVolf
6f78523bf0 unlimited unlock 2016-03-28 02:15:12 +02:00
Gav Wood
5dbbf9db13 Allow passwords on multiple lines in --password files. 2016-03-28 02:13:47 +02:00
Gav Wood
0d6ffa2a97 Minor refactor. 2016-03-28 02:13:47 +02:00
Gav Wood
3afb6370f9 Unlock accounts on CLI. 2016-03-28 02:13:47 +02:00
Gav Wood
dad4bfecdf Merge pull request #828 from ethcore/optionalblocknumberinrpc
Make BlockNumber optional, fix eth_call
2016-03-26 23:29:45 +01:00
Gav Wood
902b44c94f Remove info!s. 2016-03-26 13:44:42 +01:00
Gav Wood
54bf237e4f Fix backport. 2016-03-26 13:31:04 +01:00
Gav Wood
f835ce8253 Fix eth_call so it doesn't need the secret of the sender. 2016-03-26 13:30:50 +01:00
Gav Wood
4d04668c48 Make BlockNumber optional. 2016-03-26 12:35:15 +01:00
Arkadiy Paronyan
b4d95089d4 Merge pull request #826 from ethcore/web3sha3-beta
Web3sha3 beta
2016-03-26 12:08:30 +01:00
Gav Wood
cca30f964e Update web3.rs
[ci-skip]
2016-03-26 11:22:29 +01:00
NikVolf
f11cc80561 wiki test 2016-03-26 11:22:23 +01:00
NikVolf
4f71fd5d4d avoid copy 2016-03-26 11:22:13 +01:00
NikVolf
0340466f5f web3_sha3 2016-03-26 11:22:06 +01:00
Nikolay Volf
8847819b31 Merge pull request #821 from ethcore/netidfix-beta
Use network id for the web3_net_version return.
2016-03-26 04:01:53 +04:00
Gav Wood
ca91fd5e76 Use network id for the web3_net_version return. 2016-03-26 00:22:09 +01:00
Arkadiy Paronyan
df2619a37d Merge pull request #806 from ethcore/tracegetwork-beta
Fix mining from spinning
2016-03-24 17:34:07 +01:00
arkpar
4840371635 Fixed test 2016-03-24 17:07:54 +01:00
Gav Wood
68e4156143 Don't care if engaged in sync since it's typically doing so. 2016-03-24 14:29:54 +00:00
Gav Wood
83f812b176 Fix logic. agaib. 2016-03-24 14:24:58 +00:00
Gav Wood
36c5525e3f Fix logic error. 2016-03-24 14:15:55 +00:00
Gav Wood
78b5c12cf9 Fix mining. 2016-03-24 14:13:43 +00:00
Gav Wood
0564e7c168 Fix compile. 2016-03-24 14:00:15 +00:00
Gav Wood
7a4e91d26d Add tracing. 2016-03-24 14:00:09 +00:00
Tomasz Drwięga
ec26827f58 Fixing future-current transactions clash 2016-03-23 14:45:02 +01:00
arkpar
01b71bf9ba Merge with master 2016-03-22 22:09:44 +01:00
Gav Wood
42040438ed Fix author reporting. num_cpus for JSONRPC threads. 2016-03-22 21:58:28 +01:00
Gav Wood
799828b51e Increase threads to 4. 2016-03-22 21:58:28 +01:00
debris
f78e8c3a38 fixed eth_call, eth_sendTransaction and eth_estimateGas 2016-03-22 21:58:28 +01:00
debris
4f242996d1 uncle 2016-03-22 21:58:28 +01:00
debris
daecf5db3e removed outdated comment 2016-03-22 21:58:28 +01:00
debris
9a09f52679 implemented eth_sendRawTransaction 2016-03-22 21:58:28 +01:00
debris
841a996fa6 test for eth_getTransactionReceipt 2016-03-22 21:58:28 +01:00
Alexander Orlov
ff99ccaf82 complete getting started steps for OS X
You get 
`multirust: no default toolchain configured` 
when 
`multirust default stable`
is not executed.
2016-03-22 21:58:28 +01:00
arkpar
60f2aadb8e Prettier version wo git dir; Use rustc compile time version 2016-03-22 21:53:29 +01:00
Tomasz Drwięga
c143b1b783 Validating senders balance before importing transaction to queue 2016-03-22 21:52:28 +01:00
Tomasz Drwięga
2377d46c59 Speeding up build 2016-03-22 21:44:58 +01:00
Arkadiy Paronyan
10d361aec5 Merge pull request #796 from ethcore/beta-staging
Merge master to beta
2016-03-22 20:55:57 +01:00
arkpar
bf4e4df4c8 Fixed sync tests 2016-03-21 18:51:22 +01:00
arkpar
3b766f01f2 Fixed rpc tests 2016-03-21 18:07:07 +01:00
arkpar
2aa3864d67 Merge with master 2016-03-21 15:55:46 +01:00
debris
04082d1514 client implementation of transaction receipt 2016-03-21 00:05:45 +01:00
debris
85fa07728c LocalizedReceipt 2016-03-21 00:05:45 +01:00
Tomasz Drwięga
a36ac996a0 Avoiding possible overflow when block number gets smaller. 2016-03-21 00:05:45 +01:00
Tomasz Drwięga
6e666ecac7 Fixing ethminer doctest 2016-03-21 00:05:45 +01:00
Tomasz Drwięga
08dc83205c Flipping sealing_enabled flag after no requests for sealing_block for some time 2016-03-21 00:05:43 +01:00
Gav Wood
bff142828d JSONRPC interface defaults to local.
Please enter the commit message for your changes. Lines starting
2016-03-21 00:04:55 +01:00
Gav Wood
6d1ae888ca Listen on all interfaces for JSONRPC by default. 2016-03-21 00:04:55 +01:00
debris
d5cc2c9e67 implemented rpc eth_estimateGas method, added tests for rpc eth_call and eth_estimateGas 2016-03-21 00:04:55 +01:00
debris
048dba7ef3 fixed indentation 2016-03-21 00:04:55 +01:00
debris
280c5e8a99 implementation of eth_estimateGas 2016-03-21 00:04:55 +01:00
debris
1257ad2993 fixes after merge 2016-03-21 00:04:55 +01:00
debris
5c72e60b14 implemented eth_call 2016-03-21 00:04:55 +01:00
debris
aa6b6e477c added output to execution result 2016-03-21 00:04:55 +01:00
Gav Wood
245ef854dd Allow 0x prefix for --author. 2016-03-21 00:04:55 +01:00
debris
c2cffd1e06 improvements to build, updated dependencies, moved rpctest to its own submodule 2016-03-21 00:04:53 +01:00
debris
ddab958e61 fixed missing import 2016-03-20 23:56:57 +01:00
debris
a10160bd56 use ethjson module to load chain json tests 2016-03-20 23:56:57 +01:00
debris
49be60e984 test ethjson module on travis 2016-03-20 23:56:57 +01:00
debris
2b8a151b82 fixed failing eth rpc tests 2016-03-20 23:56:57 +01:00
debris
9bcc6c9e69 next batch of rpc fixes, 103 still failing 2016-03-20 23:56:57 +01:00
debris
0fc605face rpc tests, now 421 passing / 116 failing 2016-03-20 23:56:57 +01:00
debris
8f1618687c fixed parsing blockchain file, added default account to rpc tests 2016-03-20 23:56:57 +01:00
debris
cb246c26c0 fixed invalid json files 2016-03-20 23:56:56 +01:00
debris
086e45671b removed warnings by adding missing documentation 2016-03-20 23:56:56 +01:00
debris
f3ad643b69 pricing { linear: {} } 2016-03-20 23:56:56 +01:00
debris
c5a4993e39 fixed failing builin test 2016-03-20 23:56:56 +01:00
debris
32cc0bddf6 fixed od builting parsing 2016-03-20 23:56:56 +01:00
debris
d87286c5c3 updated rpc helpers docs 2016-03-20 23:56:56 +01:00
debris
ac3acdef71 linear -> pricing 2016-03-20 23:56:56 +01:00
debris
dffa9bcef6 fixed compilation with --release flag 2016-03-20 23:56:56 +01:00
debris
9ce75a173e fixed name of rpctest executable in rpctest --help 2016-03-20 23:56:56 +01:00
debris
755faf37e3 running rpc tests 2016-03-20 23:56:56 +01:00
debris
de21fef868 new way of loading PodState 2016-03-20 23:56:56 +01:00
debris
39aa02ed26 moved ethcores spec to its own module, added genesis 2016-03-20 23:56:54 +01:00
debris
7a0dfec115 added genesis method to ethjson blockchain 2016-03-20 23:54:53 +01:00
debris
1fa019d92a ethjson spec submodule 2016-03-20 23:54:53 +01:00
debris
7105ed3f61 rpctest executable 2016-03-20 23:54:53 +01:00
Tomasz Drwięga
2f411c93fd Removing update_seal when new transactions arrives 2016-03-20 23:54:53 +01:00
Tomasz Drwięga
808f959a94 Common error handling 2016-03-20 23:54:51 +01:00
Tomasz Drwięga
2aae862330 Updating sealing when new transactions are received 2016-03-20 23:54:24 +01:00
Tomasz Drwięga
b18a7bde9a Updating gas_limit in test_client generated blocks 2016-03-20 23:53:23 +01:00
Tomasz Drwięga
a0cdf5c420 Ignoring transactions slightly above gas_limit 2016-03-20 23:53:21 +01:00
Tomasz Drwięga
b3dd72ab0a BlockGasLimit taken from push_transaction result 2016-03-20 23:52:58 +01:00
Tomasz Drwięga
4d984ead4f Fixing compilation 2016-03-20 23:52:58 +01:00
Tomasz Drwięga
fbc85e31c2 Refactoring removing invalid transactions from queue 2016-03-20 23:52:58 +01:00
Tomasz Drwięga
177d26a25e Stop adding transactions right after we know that no other will make it to block. 2016-03-20 23:52:58 +01:00
Tomasz Drwięga
1f363b22fc Removing invalid transactions from queue 2016-03-20 23:52:58 +01:00
Tomasz Drwięga
5aed421fa3 Removing allow dead_code 2016-03-20 23:52:58 +01:00
Tomasz Drwięga
f4df9c8dfd Fixing warnings 2016-03-20 23:52:58 +01:00
Tomasz Drwięga
144385e67d Bumping clippy 2016-03-20 23:52:56 +01:00
Tomasz Drwięga
9b6abb5861 Attempting to add all transactions to mined block 2016-03-20 23:52:31 +01:00
arkpar
6c81f1fb74 Prettier version wo git dir; Use rustc compile time version 2016-03-20 23:52:29 +01:00
Nikolay Volf
7371beb26c get rid of the function 2016-03-20 23:52:00 +01:00
Nikolay Volf
7acdc80b27 propagation is out 2016-03-20 23:51:59 +01:00
Nikolay Volf
3847f8a9fc no flag also 2016-03-20 23:51:58 +01:00
Tomasz Drwięga
56e977b425 Fixing doctest 2016-03-20 23:51:22 +01:00
Tomasz Drwięga
2f8e6be2ea Adding missing commas 2016-03-20 23:51:22 +01:00
Tomasz Drwięga
180debb260 Reverting check if block queue is empty 2016-03-20 23:51:22 +01:00
Tomasz Drwięga
b79c7f05c0 Increasing balance in tests 2016-03-20 23:51:22 +01:00
Tomasz Drwięga
d17c629b71 Full transaction cost 2016-03-20 23:51:22 +01:00
Tomasz Drwięga
4be4a1c151 Fixing sync test 2016-03-20 23:51:22 +01:00
Tomasz Drwięga
b0d7d48391 Adding test 2016-03-20 23:51:22 +01:00
Tomasz Drwięga
164cd268ad Fixing build 2016-03-20 23:51:22 +01:00
Tomasz Drwięga
3a16ef19c1 Removing unused import 2016-03-20 23:51:22 +01:00
Tomasz Drwięga
74ea9cc74c Validating senders balance before importing transaction to queue 2016-03-20 23:51:22 +01:00
Tomasz Drwięga
2e88183df4 Removing printlns 2016-03-20 23:51:22 +01:00
Tomasz Drwięga
fca8eb5810 Importing transactions from hashset. Notifying about every block 2016-03-20 23:51:22 +01:00
Tomasz Drwięga
df4b326cb3 Adding missing space 2016-03-20 23:51:22 +01:00
Tomasz Drwięga
4db397ecb1 Renaming status fields to something more descriptive. 2016-03-20 23:51:20 +01:00
Tomasz Drwięga
e767fd88f6 Returning number of transactions pending in block not queue 2016-03-20 23:50:59 +01:00
Tomasz Drwięga
fae7039fda Disabling benches and beta tests 2016-03-20 23:50:59 +01:00
Tomasz Drwięga
69d6f3ed3e Enabling fast finish 2016-03-20 23:50:59 +01:00
Tomasz Drwięga
4292e75dca More cleaning 2016-03-20 23:50:59 +01:00
Tomasz Drwięga
2b4640c94c Cleaning 2016-03-20 23:50:59 +01:00
Tomasz Drwięga
42a6954ec9 Speeding up build 2016-03-20 23:50:57 +01:00
Nikolay Volf
114bab66c4 overhaul to flag 2016-03-20 23:50:31 +01:00
Nikolay Volf
13d0d6d006 adding helper can_sync 2016-03-20 23:50:31 +01:00
debris
c15e78cd95 tests for loading test json files 2016-03-20 23:50:31 +01:00
debris
24993b8d4e finished blockchain test deserialization 2016-03-20 23:50:31 +01:00
debris
69d89583ca proper blockchain json parsing 2016-03-20 23:50:29 +01:00
Arkadiy Paronyan
3c8fb60cbd Update install-parity.sh 2016-03-20 23:49:34 +01:00
arkpar
9f8a131fa4 restart sync on getting old unknown header 2016-03-20 23:49:34 +01:00
Nikolay Volf
31f4a214a9 adding message from client to sync and disabling sending transactions to the queue while syncing 2016-03-20 23:49:34 +01:00
Gav Wood
81f8f939b9 Update sync_provider.rs 2016-03-20 23:49:34 +01:00
Nikolay Volf
28e4847b59 tests 2016-03-20 23:49:34 +01:00
Nikolay Volf
30ecff3959 checking queue also 2016-03-20 23:49:34 +01:00
Nikolay Volf
8add773b12 [ci skip] grammar fix 2016-03-20 23:49:34 +01:00
Nikolay Volf
c20e761051 adding check for a sync 2016-03-20 23:49:34 +01:00
arkpar
35be0e9943 Indent 2016-03-17 19:40:08 +01:00
arkpar
3bf0a00ba4 Prettier version wo git dir; Use rustc compile time version 2016-03-17 19:39:54 +01:00
arkpar
570d2c21d3 Merge branch 'sync' into beta 2016-03-15 19:44:15 +01:00
arkpar
b9fc5bdda0 Merge remote-tracking branch 'origin/transaction_queue_race' into beta 2016-03-15 12:56:30 +01:00
arkpar
1964ed7eb3 Merge remote-tracking branch 'origin/sync' into beta 2016-03-15 12:56:17 +01:00
arkpar
60bcab3e48 Merge remote-tracking branch 'origin/docker' into beta 2016-03-14 19:13:07 +01:00
arkpar
ebb7699da2 Merge remote-tracking branch 'origin/pv63-receipts' into beta 2016-03-14 18:58:23 +01:00
arkpar
78821bb935 Merge remote-tracking branch 'origin/unclesminingfix' into beta 2016-03-14 18:56:27 +01:00
arkpar
e8a21116f7 missing mut 2016-03-14 15:50:45 +01:00
Gav Wood
9f81b07224 Lock reports to avoid out of order badness. 2016-03-14 15:50:32 +01:00
arkpar
8eeda2b1a3 Fixed handshake leak 2016-03-14 15:50:03 +01:00
Arkadiy Paronyan
0087568c16 Merge pull request #712 from ethcore/beta-version
Version 1.0 in beta
2016-03-14 14:56:44 +01:00
arkpar
75a11ba9be Merge remote-tracking branch 'origin/targetgaslimit' into beta 2016-03-14 14:05:38 +01:00
Nikolay Volf
4ac9807bc1 fixing tests for beta 2016-03-14 11:12:15 +01:00
arkpar
1c26ffa208 Merge branch 'network' into beta 2016-03-14 11:11:36 +01:00
arkpar
f8b18d5d7b Merge remote-tracking branch 'origin/rpc-personal-tests' into beta 2016-03-14 10:30:22 +01:00
arkpar
b327e79b42 Merge remote-tracking branch 'origin/fixing_warnings' into beta 2016-03-14 10:28:38 +01:00
arkpar
8e2f35856a Merge remote-tracking branch 'origin/docoptclean' into beta 2016-03-14 10:26:59 +01:00
arkpar
a029551b0b Merge branch 'build' into beta 2016-03-14 09:56:44 +01:00
arkpar
320581a3e4 Merge branch 'fix-discovery' into beta 2016-03-14 01:33:41 +01:00
arkpar
f77b4119da Version 1.0 2016-03-14 01:01:15 +01:00
120 changed files with 4191 additions and 714 deletions

View File

@@ -8,20 +8,46 @@ branches:
- /^stable-.*$/
- /^beta$/
- /^stable$/
git:
depth: 3
matrix:
fast_finish: false
fast_finish: true
allow_failures:
- rust: nightly
include:
- rust: stable
env: FEATURES="--features travis-beta" KCOV_FEATURES="" TARGETS="-p ethash -p ethcore-util -p ethcore -p ethsync -p ethcore-rpc -p parity -p ethminer" ARCHIVE_SUFFIX="-${TRAVIS_OS_NAME}-${TRAVIS_TAG}"
env: FEATURES="--features travis-beta" RUN_TESTS="true"
# - rust: beta
# env: FEATURES="--features travis-beta" RUN_TESTS="true"
- rust: stable
env: FEATURES="--features travis-beta" RUN_BUILD="true"
- rust: beta
env: FEATURES="--features travis-beta" RUN_BUILD="true"
- rust: stable
env: FEATURES="--features travis-beta" RUN_COVERAGE="true"
# - rust: nightly
# env: FEATURES="--features travis-nightly" RUN_BENCHES="true"
- rust: nightly
env: FEATURES="--features travis-nightly" RUN_TESTS="true"
env:
global:
# GH_TOKEN
- secure: bumJASbZSU8bxJ0EyPUJmu16AiV9EXOpyOj86Jlq/Ty9CfwGqsSXt96uDyE+OUJf34RUFQMsw0nk37/zC4lcn6kqk2wpuH3N/o85Zo/cVZY/NusBWLQqtT5VbYWsV+u2Ua4Tmmsw8yVYQhYwU2ZOejNpflL+Cs9XGgORp1L+/gMRMC2y5Se6ZhwnKPQlRJ8LGsG1dzjQULxzADIt3/zuspNBS8a2urJwlHfGMkvHDoUWCviP/GXoSqw3TZR7FmKyxE19I8n9+iSvm9+oZZquvcgfUxMHn8Gq/b44UbPvjtFOg2yam4xdWXF/RyWCHdc/R9EHorSABeCbefIsm+zcUF3/YQxwpSxM4IZEeH2rTiC7dcrsKw3XsO16xFQz5YI5Bay+CT/wTdMmJd7DdYz7Dyf+pOvcM9WOf/zorxYWSBOMYy0uzbusU2iyIghQ82s7E/Ahg+WARtPgkuTLSB5aL1oCTBKHqQscMr7lo5Ti6RpWLxEdTQMBznc+bMr+6dEtkEcG9zqc6cE9XX+ox3wTU6+HVMfQ1ltCntJ4UKcw3A6INEbw9wgocQa812CIASQ2fE+SCAbz6JxBjIAlFUnD1lUB7S8PdMPwn9plfQgKQ2A5YZqg6FnBdf0rQXIJYxQWKHXj/rBHSUCT0tHACDlzTA+EwWggvkP5AGIxRxm8jhw=
- CVER=5
- NUM_JOBS=1
# - TARGETS="-p ethash -p ethcore-util -p ethcore -p ethsync -p ethcore-rpc -p parity -p ethminer"
- TARGETS="-p ethcore-util"
- ARCHIVE_SUFFIX="-${TRAVIS_OS_NAME}-${TRAVIS_TAG}"
- KCOV_FEATURES=""
- KCOV_CMD="./kcov-master/tmp/usr/local/bin/kcov --exclude-pattern /usr/,/.cargo,/root/.multirust,src/tests,util/json-tests,util/src/network/tests,sync/src/tests,ethcore/src/tests,ethcore/src/evm/tests target/kcov"
- RUN_TESTS="false"
- RUN_COVERAGE="false"
- RUN_BUILD="false"
- RUN_BENCHES="false"
cache:
apt: true
directories:
- target/debug/deps
- target/debug/build
- target/release/deps
- target/release/build
- $TRAVIS_BUILD_DIR/target
- $HOME/.cargo
addons:
apt:
@@ -29,22 +55,27 @@ addons:
- libcurl4-openssl-dev
- libelf-dev
- libdw-dev
script:
- cargo build --release --verbose ${FEATURES}
- cargo test --release --verbose ${FEATURES} ${TARGETS}
#- cargo bench --no-run ${FEATURES} ${TARGETS}
- tar cvzf parity${ARCHIVE_SUFFIX}.tar.gz -C target/release parity
- echo "$TRAVIS_BUILD_DIR/target"
- ls "$TRAVIS_BUILD_DIR/target"
- if [ "$RUN_TESTS" = "true" ]; then cargo test --release --verbose ${FEATURES} ${TARGETS}; fi
- if [ "$RUN_BENCHES" = "true" ]; then cargo bench --no-run ${FEATURES} ${TARGETS}; fi
- if [ "$RUN_BUILD" = "true" ]; then cargo build --release --verbose ${FEATURES}; fi
- if [ "$RUN_BUILD" = "true" ]; then tar cvzf parity${ARCHIVE_SUFFIX}.tar.gz -C target/release parity; fi
after_success: |
[ "$RUN_COVERAGE" = "true" ] &&
wget https://github.com/SimonKagstrom/kcov/archive/master.tar.gz &&
tar xzf master.tar.gz && mkdir kcov-master/build && cd kcov-master/build && cmake .. && make && make install DESTDIR=../tmp && cd ../.. &&
cargo test --no-run ${KCOV_FEATURES} ${TARGETS} &&
./kcov-master/tmp/usr/local/bin/kcov --exclude-pattern /usr/,/.cargo,/root/.multirust,src/tests,util/json-tests,util/src/network/tests,sync/src/tests,ethcore/src/tests,ethcore/src/evm/tests target/kcov target/debug/deps/ethcore_util-* &&
./kcov-master/tmp/usr/local/bin/kcov --exclude-pattern /usr/,/.cargo,/root/.multirust,src/tests,util/json-tests,util/src/network/tests,sync/src/tests,ethcore/src/tests,ethcore/src/evm/tests target/kcov target/debug/deps/ethash-* &&
./kcov-master/tmp/usr/local/bin/kcov --exclude-pattern /usr/,/.cargo,/root/.multirust,src/tests,util/json-tests,util/src/network/tests,sync/src/tests,ethcore/src/tests,ethcore/src/evm/tests target/kcov target/debug/deps/ethcore-* &&
./kcov-master/tmp/usr/local/bin/kcov --exclude-pattern /usr/,/.cargo,/root/.multirust,src/tests,util/json-tests,util/src/network/tests,sync/src/tests,ethcore/src/tests,ethcore/src/evm/tests target/kcov target/debug/deps/ethsync-* &&
./kcov-master/tmp/usr/local/bin/kcov --exclude-pattern /usr/,/.cargo,/root/.multirust,src/tests,util/json-tests,util/src/network/tests,sync/src/tests,ethcore/src/tests,ethcore/src/evm/tests target/kcov target/debug/deps/ethcore_rpc-* &&
./kcov-master/tmp/usr/local/bin/kcov --exclude-pattern /usr/,/.cargo,/root/.multirust,src/tests,util/json-tests,util/src/network/tests,sync/src/tests,ethcore/src/tests,ethcore/src/evm/tests target/kcov target/debug/deps/ethminer-* &&
./kcov-master/tmp/usr/local/bin/kcov --coveralls-id=${TRAVIS_JOB_ID} --exclude-pattern /usr/,/.cargo,/root/.multirust target/kcov target/debug/parity-* &&
$KCOV_CMD target/debug/deps/ethcore_util-* &&
$KCOV_CMD target/debug/deps/ethash-* &&
$KCOV_CMD target/debug/deps/ethcore-* &&
$KCOV_CMD target/debug/deps/ethsync-* &&
$KCOV_CMD target/debug/deps/ethcore_rpc-* &&
$KCOV_CMD target/debug/deps/ethminer-* &&
$KCOV_CMD target/debug/parity-* &&
[ $TRAVIS_BRANCH = master ] &&
[ $TRAVIS_PULL_REQUEST = false ] &&
[ $TRAVIS_RUST_VERSION = stable ] &&
@@ -53,10 +84,6 @@ after_success: |
pip install --user ghp-import &&
/home/travis/.local/bin/ghp-import -n target/doc &&
git push -fq https://${GH_TOKEN}@github.com/${TRAVIS_REPO_SLUG}.git gh-pages
env:
global:
# GH_TOKEN
- secure: bumJASbZSU8bxJ0EyPUJmu16AiV9EXOpyOj86Jlq/Ty9CfwGqsSXt96uDyE+OUJf34RUFQMsw0nk37/zC4lcn6kqk2wpuH3N/o85Zo/cVZY/NusBWLQqtT5VbYWsV+u2Ua4Tmmsw8yVYQhYwU2ZOejNpflL+Cs9XGgORp1L+/gMRMC2y5Se6ZhwnKPQlRJ8LGsG1dzjQULxzADIt3/zuspNBS8a2urJwlHfGMkvHDoUWCviP/GXoSqw3TZR7FmKyxE19I8n9+iSvm9+oZZquvcgfUxMHn8Gq/b44UbPvjtFOg2yam4xdWXF/RyWCHdc/R9EHorSABeCbefIsm+zcUF3/YQxwpSxM4IZEeH2rTiC7dcrsKw3XsO16xFQz5YI5Bay+CT/wTdMmJd7DdYz7Dyf+pOvcM9WOf/zorxYWSBOMYy0uzbusU2iyIghQ82s7E/Ahg+WARtPgkuTLSB5aL1oCTBKHqQscMr7lo5Ti6RpWLxEdTQMBznc+bMr+6dEtkEcG9zqc6cE9XX+ox3wTU6+HVMfQ1ltCntJ4UKcw3A6INEbw9wgocQa812CIASQ2fE+SCAbz6JxBjIAlFUnD1lUB7S8PdMPwn9plfQgKQ2A5YZqg6FnBdf0rQXIJYxQWKHXj/rBHSUCT0tHACDlzTA+EwWggvkP5AGIxRxm8jhw=
deploy:
provider: releases

257
Cargo.lock generated
View File

@@ -1,20 +1,21 @@
[root]
name = "parity"
version = "1.1.0"
version = "1.0.2"
dependencies = [
"clippy 0.0.50 (registry+https://github.com/rust-lang/crates.io-index)",
"clippy 0.0.54 (registry+https://github.com/rust-lang/crates.io-index)",
"ctrlc 1.1.1 (git+https://github.com/tomusdrw/rust-ctrlc.git)",
"daemonize 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
"docopt 0.6.78 (registry+https://github.com/rust-lang/crates.io-index)",
"env_logger 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)",
"ethcore 1.1.0",
"ethcore-devtools 1.1.0",
"ethcore-rpc 1.1.0",
"ethcore-util 1.1.0",
"ethminer 1.1.0",
"ethsync 1.1.0",
"ethcore 1.0.2",
"ethcore-devtools 1.0.0",
"ethcore-rpc 1.0.2",
"ethcore-util 1.0.2",
"ethminer 1.0.0",
"ethsync 1.0.2",
"fdlimit 0.1.0",
"log 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)",
"num_cpus 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)",
"number_prefix 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)",
"rpassword 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
"rustc-serialize 0.3.18 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -41,10 +42,10 @@ dependencies = [
[[package]]
name = "aster"
version = "0.13.1"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"syntex_syntax 0.29.1 (registry+https://github.com/rust-lang/crates.io-index)",
"syntex_syntax 0.30.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
@@ -52,7 +53,7 @@ name = "bigint"
version = "0.1.0"
dependencies = [
"arrayvec 0.3.16 (registry+https://github.com/rust-lang/crates.io-index)",
"heapsize 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)",
"heapsize 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)",
"rand 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)",
"rustc-serialize 0.3.18 (registry+https://github.com/rust-lang/crates.io-index)",
"rustc_version 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -95,11 +96,12 @@ dependencies = [
[[package]]
name = "clippy"
version = "0.0.50"
version = "0.0.54"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"regex-syntax 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)",
"regex-syntax 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
"semver 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)",
"toml 0.1.28 (registry+https://github.com/rust-lang/crates.io-index)",
"unicode-normalization 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
]
@@ -138,7 +140,7 @@ source = "git+https://github.com/tomusdrw/rust-ctrlc.git#f4927770f89eca80ec25091
dependencies = [
"kernel32-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
@@ -162,7 +164,7 @@ name = "docopt"
version = "0.6.78"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"regex 0.1.56 (registry+https://github.com/rust-lang/crates.io-index)",
"regex 0.1.58 (registry+https://github.com/rust-lang/crates.io-index)",
"rustc-serialize 0.3.18 (registry+https://github.com/rust-lang/crates.io-index)",
"strsim 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
@@ -178,7 +180,7 @@ version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"log 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)",
"regex 0.1.56 (registry+https://github.com/rust-lang/crates.io-index)",
"regex 0.1.58 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
@@ -197,7 +199,7 @@ dependencies = [
[[package]]
name = "ethash"
version = "1.1.0"
version = "1.0.0"
dependencies = [
"log 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)",
"primal 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -206,15 +208,16 @@ dependencies = [
[[package]]
name = "ethcore"
version = "1.1.0"
version = "1.0.2"
dependencies = [
"clippy 0.0.50 (registry+https://github.com/rust-lang/crates.io-index)",
"clippy 0.0.54 (registry+https://github.com/rust-lang/crates.io-index)",
"crossbeam 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)",
"env_logger 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)",
"ethash 1.1.0",
"ethcore-devtools 1.1.0",
"ethcore-util 1.1.0",
"heapsize 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)",
"ethash 1.0.0",
"ethcore-devtools 1.0.0",
"ethcore-util 1.0.2",
"ethjson 0.1.0",
"heapsize 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)",
"lazy_static 0.1.15 (registry+https://github.com/rust-lang/crates.io-index)",
"log 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)",
"num_cpus 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -225,46 +228,46 @@ dependencies = [
[[package]]
name = "ethcore-devtools"
version = "1.1.0"
version = "1.0.0"
dependencies = [
"rand 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "ethcore-rpc"
version = "1.1.0"
version = "1.0.2"
dependencies = [
"clippy 0.0.50 (registry+https://github.com/rust-lang/crates.io-index)",
"ethash 1.1.0",
"ethcore 1.1.0",
"ethcore-util 1.1.0",
"ethminer 1.1.0",
"ethsync 1.1.0",
"jsonrpc-core 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
"jsonrpc-http-server 3.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
"clippy 0.0.54 (registry+https://github.com/rust-lang/crates.io-index)",
"ethash 1.0.0",
"ethcore 1.0.2",
"ethcore-util 1.0.2",
"ethminer 1.0.0",
"ethsync 1.0.2",
"jsonrpc-core 2.0.1 (registry+https://github.com/rust-lang/crates.io-index)",
"jsonrpc-http-server 5.0.0 (git+https://github.com/debris/jsonrpc-http-server.git)",
"log 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)",
"rustc-serialize 0.3.18 (registry+https://github.com/rust-lang/crates.io-index)",
"serde 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)",
"serde_codegen 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)",
"serde_codegen 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)",
"serde_json 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)",
"syntex 0.29.0 (registry+https://github.com/rust-lang/crates.io-index)",
"syntex 0.30.0 (registry+https://github.com/rust-lang/crates.io-index)",
"transient-hashmap 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "ethcore-util"
version = "1.1.0"
version = "1.0.2"
dependencies = [
"arrayvec 0.3.16 (registry+https://github.com/rust-lang/crates.io-index)",
"bigint 0.1.0",
"chrono 0.2.20 (registry+https://github.com/rust-lang/crates.io-index)",
"clippy 0.0.50 (registry+https://github.com/rust-lang/crates.io-index)",
"clippy 0.0.54 (registry+https://github.com/rust-lang/crates.io-index)",
"crossbeam 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)",
"elastic-array 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
"env_logger 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)",
"eth-secp256k1 0.5.4 (git+https://github.com/ethcore/rust-secp256k1)",
"ethcore-devtools 1.1.0",
"heapsize 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)",
"ethcore-devtools 1.0.0",
"heapsize 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)",
"igd 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)",
"itertools 0.4.11 (registry+https://github.com/rust-lang/crates.io-index)",
"json-tests 0.1.0",
@@ -287,13 +290,25 @@ dependencies = [
]
[[package]]
name = "ethminer"
version = "1.1.0"
name = "ethjson"
version = "0.1.0"
dependencies = [
"clippy 0.0.50 (registry+https://github.com/rust-lang/crates.io-index)",
"ethcore-util 1.0.2",
"rustc-serialize 0.3.18 (registry+https://github.com/rust-lang/crates.io-index)",
"serde 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)",
"serde_codegen 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)",
"serde_json 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)",
"syntex 0.30.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "ethminer"
version = "1.0.0"
dependencies = [
"clippy 0.0.54 (registry+https://github.com/rust-lang/crates.io-index)",
"env_logger 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)",
"ethcore 1.1.0",
"ethcore-util 1.1.0",
"ethcore 1.0.2",
"ethcore-util 1.0.2",
"log 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)",
"rayon 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)",
"rustc-serialize 0.3.18 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -302,14 +317,14 @@ dependencies = [
[[package]]
name = "ethsync"
version = "1.1.0"
version = "1.0.2"
dependencies = [
"clippy 0.0.50 (registry+https://github.com/rust-lang/crates.io-index)",
"clippy 0.0.54 (registry+https://github.com/rust-lang/crates.io-index)",
"env_logger 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)",
"ethcore 1.1.0",
"ethcore-util 1.1.0",
"ethminer 1.1.0",
"heapsize 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)",
"ethcore 1.0.2",
"ethcore-util 1.0.2",
"ethminer 1.0.0",
"heapsize 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)",
"log 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)",
"rand 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)",
"time 0.1.34 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -339,11 +354,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "heapsize"
version = "0.3.3"
version = "0.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"kernel32-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
"regex 0.1.56 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
@@ -375,28 +389,29 @@ dependencies = [
"time 0.1.34 (registry+https://github.com/rust-lang/crates.io-index)",
"traitobject 0.0.1 (registry+https://github.com/rust-lang/crates.io-index)",
"typeable 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
"unicase 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
"unicase 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
"url 0.2.38 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "hyper"
version = "0.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
version = "0.9.0-mio"
source = "git+https://github.com/hyperium/hyper?branch=mio#bf42e7563b7d52f334a1b25ec3dccf031febb990"
dependencies = [
"cookie 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
"httparse 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
"language-tags 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
"log 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)",
"mime 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
"num_cpus 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)",
"mio 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)",
"rotor 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)",
"rustc-serialize 0.3.18 (registry+https://github.com/rust-lang/crates.io-index)",
"solicit 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)",
"time 0.1.34 (registry+https://github.com/rust-lang/crates.io-index)",
"traitobject 0.0.1 (registry+https://github.com/rust-lang/crates.io-index)",
"typeable 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
"unicase 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
"unicase 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
"url 0.5.7 (registry+https://github.com/rust-lang/crates.io-index)",
"vecio 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
@@ -406,7 +421,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"hyper 0.6.16 (registry+https://github.com/rust-lang/crates.io-index)",
"rand 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)",
"regex 0.1.56 (registry+https://github.com/rust-lang/crates.io-index)",
"regex 0.1.58 (registry+https://github.com/rust-lang/crates.io-index)",
"xml-rs 0.1.26 (registry+https://github.com/rust-lang/crates.io-index)",
"xmltree 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
@@ -426,23 +441,23 @@ dependencies = [
[[package]]
name = "jsonrpc-core"
version = "2.0.0"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"serde 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)",
"serde_codegen 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)",
"serde_codegen 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)",
"serde_json 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)",
"syntex 0.29.0 (registry+https://github.com/rust-lang/crates.io-index)",
"syntex 0.30.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "jsonrpc-http-server"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
version = "5.0.0"
source = "git+https://github.com/debris/jsonrpc-http-server.git#76fa443982b40665721fe6b1ece42fc0a53be996"
dependencies = [
"hyper 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)",
"jsonrpc-core 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
"unicase 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
"hyper 0.9.0-mio (git+https://github.com/hyperium/hyper?branch=mio)",
"jsonrpc-core 2.0.1 (registry+https://github.com/rust-lang/crates.io-index)",
"unicase 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
@@ -450,7 +465,7 @@ name = "kernel32-sys"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"winapi 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi-build 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
@@ -482,7 +497,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "librocksdb-sys"
version = "0.2.3"
source = "git+https://github.com/arkpar/rust-rocksdb.git#ebb602fc74b4067f9f51310bdc0401b8e59b7156"
source = "git+https://github.com/arkpar/rust-rocksdb.git#ae44ef33ed1358ffc79aa05ed77839d555daba33"
dependencies = [
"libc 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)",
]
@@ -526,11 +541,11 @@ dependencies = [
"libc 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)",
"log 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)",
"miow 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
"net2 0.2.22 (registry+https://github.com/rust-lang/crates.io-index)",
"net2 0.2.23 (registry+https://github.com/rust-lang/crates.io-index)",
"nix 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)",
"slab 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
"time 0.1.34 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
@@ -539,20 +554,20 @@ version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"kernel32-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
"net2 0.2.22 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)",
"net2 0.2.23 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)",
"ws2_32-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "net2"
version = "0.2.22"
version = "0.2.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"cfg-if 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
"kernel32-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)",
"ws2_32-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
@@ -651,22 +666,27 @@ dependencies = [
[[package]]
name = "quasi"
version = "0.7.0"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"syntex_syntax 0.29.1 (registry+https://github.com/rust-lang/crates.io-index)",
"syntex_syntax 0.30.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "quasi_codegen"
version = "0.7.0"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"aster 0.13.1 (registry+https://github.com/rust-lang/crates.io-index)",
"syntex 0.29.0 (registry+https://github.com/rust-lang/crates.io-index)",
"syntex_syntax 0.29.1 (registry+https://github.com/rust-lang/crates.io-index)",
"aster 0.14.0 (registry+https://github.com/rust-lang/crates.io-index)",
"syntex 0.30.0 (registry+https://github.com/rust-lang/crates.io-index)",
"syntex_syntax 0.30.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "quick-error"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "rand"
version = "0.3.14"
@@ -687,7 +707,7 @@ dependencies = [
[[package]]
name = "regex"
version = "0.1.56"
version = "0.1.58"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"aho-corasick 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -696,11 +716,6 @@ dependencies = [
"utf8-ranges 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "regex-syntax"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "regex-syntax"
version = "0.3.0"
@@ -709,12 +724,24 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "rocksdb"
version = "0.4.3"
source = "git+https://github.com/arkpar/rust-rocksdb.git#ebb602fc74b4067f9f51310bdc0401b8e59b7156"
source = "git+https://github.com/arkpar/rust-rocksdb.git#ae44ef33ed1358ffc79aa05ed77839d555daba33"
dependencies = [
"libc 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)",
"librocksdb-sys 0.2.3 (git+https://github.com/arkpar/rust-rocksdb.git)",
]
[[package]]
name = "rotor"
version = "0.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"log 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)",
"mio 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)",
"quick-error 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
"time 0.1.34 (registry+https://github.com/rust-lang/crates.io-index)",
"void 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "rpassword"
version = "0.1.3"
@@ -723,7 +750,7 @@ dependencies = [
"kernel32-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)",
"termios 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
@@ -779,14 +806,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "serde_codegen"
version = "0.7.0"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"aster 0.13.1 (registry+https://github.com/rust-lang/crates.io-index)",
"quasi 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)",
"quasi_codegen 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)",
"syntex 0.29.0 (registry+https://github.com/rust-lang/crates.io-index)",
"syntex_syntax 0.29.1 (registry+https://github.com/rust-lang/crates.io-index)",
"aster 0.14.0 (registry+https://github.com/rust-lang/crates.io-index)",
"quasi 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)",
"quasi_codegen 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)",
"syntex 0.30.0 (registry+https://github.com/rust-lang/crates.io-index)",
"syntex_syntax 0.30.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
@@ -826,18 +853,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "syntex"
version = "0.29.0"
version = "0.30.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"syntex_syntax 0.29.1 (registry+https://github.com/rust-lang/crates.io-index)",
"syntex_syntax 0.30.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "syntex_syntax"
version = "0.29.1"
version = "0.30.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"bitflags 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)",
"bitflags 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)",
"log 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)",
"rustc-serialize 0.3.18 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -856,7 +883,7 @@ version = "0.2.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"kernel32-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
@@ -874,7 +901,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"kernel32-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
@@ -882,6 +909,14 @@ name = "tiny-keccak"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "toml"
version = "0.1.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"rustc-serialize 0.3.18 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "traitobject"
version = "0.0.1"
@@ -902,7 +937,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "unicase"
version = "1.3.0"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"rustc_version 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -962,6 +997,15 @@ dependencies = [
"rustc-serialize 0.3.18 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "vecio"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"winapi 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)",
"ws2_32-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "vergen"
version = "0.1.0"
@@ -971,9 +1015,14 @@ dependencies = [
"time 0.1.34 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "void"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "winapi"
version = "0.2.5"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
@@ -986,7 +1035,7 @@ name = "ws2_32-sys"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"winapi 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)",
"winapi-build 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
]

View File

@@ -1,7 +1,7 @@
[package]
description = "Ethcore client."
name = "parity"
version = "1.1.0"
version = "1.0.2"
license = "GPL-3.0"
authors = ["Ethcore <admin@ethcore.io>"]
build = "build.rs"
@@ -18,9 +18,10 @@ time = "0.1"
ctrlc = { git = "https://github.com/tomusdrw/rust-ctrlc.git" }
fdlimit = { path = "util/fdlimit" }
daemonize = "0.2"
num_cpus = "0.2"
number_prefix = "0.2"
rpassword = "0.1"
clippy = { version = "0.0.50", optional = true }
clippy = { version = "0.0.54", optional = true }
ethcore = { path = "ethcore" }
ethcore-util = { path = "util" }
ethsync = { path = "sync" }

View File

@@ -25,6 +25,7 @@ curl -sf https://raw.githubusercontent.com/brson/multirust/master/quick-install.
- OSX with Homebrew:
```bash
brew update && brew install multirust
multirust default stable
```
Then, download and build Parity:

View File

@@ -3,7 +3,7 @@ description = "Ethcore development/test/build tools"
homepage = "http://ethcore.io"
license = "GPL-3.0"
name = "ethcore-devtools"
version = "1.1.0"
version = "1.0.0"
authors = ["Ethcore <admin@ethcore.io>"]
[dependencies]

View File

@@ -1,6 +1,6 @@
[package]
name = "ethash"
version = "1.1.0"
version = "1.0.0"
authors = ["arkpar <arkadiy@ethcore.io"]
[lib]

View File

@@ -3,7 +3,7 @@ description = "Ethcore library"
homepage = "http://ethcore.io"
license = "GPL-3.0"
name = "ethcore"
version = "1.1.0"
version = "1.0.2"
authors = ["Ethcore <admin@ethcore.io>"]
[dependencies]
@@ -17,10 +17,11 @@ ethcore-util = { path = "../util" }
evmjit = { path = "../evmjit", optional = true }
ethash = { path = "../ethash" }
num_cpus = "0.2"
clippy = { version = "0.0.50", optional = true }
clippy = { version = "0.0.54", optional = true }
crossbeam = "0.1.5"
lazy_static = "0.1"
ethcore-devtools = { path = "../devtools" }
ethjson = { path = "../json" }
[features]
jit = ["evmjit"]

View File

@@ -30,13 +30,13 @@
"enode://a979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c@52.16.188.185:30303",
"enode://de471bccee3d042261d52e9bff31458daecc406142b401d4cd848f677479f73104b9fdeb090af9583d3391b7f10cb2ba9e26865dd5fca4fcdc0fb1e3b723c786@54.94.239.50:30303",
"enode://1118980bf48b0a3640bdba04e0fe78b1add18e1cd99bf22d53daac1fd9972ad650df52176e7c7d89d1114cfef2bc23a2959aa54998a46afcf7d91809f0855082@52.74.57.123:30303",
"enode://248f12bc8b18d5289358085520ac78cd8076485211e6d96ab0bc93d6cd25442db0ce3a937dc404f64f207b0b9aed50e25e98ce32af5ac7cb321ff285b97de485@parity-node-zero.ethcore.io:30303"
"enode://248f12bc8b18d5289358085520ac78cd8076485211e6d96ab0bc93d6cd25442db0ce3a937dc404f64f207b0b9aed50e25e98ce32af5ac7cb321ff285b97de485@zero.parity.io:30303"
],
"accounts": {
"0000000000000000000000000000000000000001": { "builtin": { "name": "ecrecover", "linear": { "base": 3000, "word": 0 } } },
"0000000000000000000000000000000000000002": { "builtin": { "name": "sha256", "linear": { "base": 60, "word": 12 } } },
"0000000000000000000000000000000000000003": { "builtin": { "name": "ripemd160", "linear": { "base": 600, "word": 120 } } },
"0000000000000000000000000000000000000004": { "builtin": { "name": "identity", "linear": { "base": 15, "word": 3 } } },
"0000000000000000000000000000000000000001": { "builtin": { "name": "ecrecover", "pricing": { "linear": { "base": 3000, "word": 0 } } } },
"0000000000000000000000000000000000000002": { "builtin": { "name": "sha256", "pricing": { "linear": { "base": 60, "word": 12 } } } },
"0000000000000000000000000000000000000003": { "builtin": { "name": "ripemd160", "pricing": { "linear": { "base": 600, "word": 120 } } } },
"0000000000000000000000000000000000000004": { "builtin": { "name": "identity", "pricing": { "linear": { "base": 15, "word": 3 } } } },
"3282791d6fd713f1e94f4bfd565eaa78b3a0599d": {
"balance": "1337000000000000000000"
},

View File

@@ -1,5 +1,5 @@
{
"engineName": "Frontier (Test)",
"name": "Frontier (Test)",
"engineName": "Ethash",
"params": {
"accountStartNonce": "0x00",
@@ -26,9 +26,9 @@
"gasLimit": "0x1388"
},
"accounts": {
"0000000000000000000000000000000000000001": { "builtin": { "name": "ecrecover", "linear": { "base": 3000, "word": 0 } } },
"0000000000000000000000000000000000000002": { "builtin": { "name": "sha256", "linear": { "base": 60, "word": 12 } } },
"0000000000000000000000000000000000000003": { "builtin": { "name": "ripemd160", "linear": { "base": 600, "word": 120 } } },
"0000000000000000000000000000000000000004": { "builtin": { "name": "identity", "linear": { "base": 15, "word": 3 } } }
"0000000000000000000000000000000000000001": { "builtin": { "name": "ecrecover", "pricing": { "linear": { "base": 3000, "word": 0 } } } },
"0000000000000000000000000000000000000002": { "builtin": { "name": "sha256", "pricing": { "linear": { "base": 60, "word": 12 } } } },
"0000000000000000000000000000000000000003": { "builtin": { "name": "ripemd160", "pricing": { "linear": { "base": 600, "word": 120 } } } },
"0000000000000000000000000000000000000004": { "builtin": { "name": "identity", "pricing": { "linear": { "base": 15, "word": 3 } } } }
}
}

View File

@@ -1,5 +1,5 @@
{
"engineName": "Frontier (Test)",
"name": "Frontier (Test)",
"engineName": "Ethash",
"params": {
"accountStartNonce": "0x00",
@@ -26,9 +26,9 @@
"gasLimit": "0x1388"
},
"accounts": {
"0000000000000000000000000000000000000001": { "builtin": { "name": "ecrecover", "linear": { "base": 3000, "word": 0 } } },
"0000000000000000000000000000000000000002": { "builtin": { "name": "sha256", "linear": { "base": 60, "word": 12 } } },
"0000000000000000000000000000000000000003": { "builtin": { "name": "ripemd160", "linear": { "base": 600, "word": 120 } } },
"0000000000000000000000000000000000000004": { "builtin": { "name": "identity", "linear": { "base": 15, "word": 3 } } }
"0000000000000000000000000000000000000001": { "builtin": { "name": "ecrecover", "pricing": { "linear": { "base": 3000, "word": 0 } } } },
"0000000000000000000000000000000000000002": { "builtin": { "name": "sha256", "pricing": { "linear": { "base": 60, "word": 12 } } } },
"0000000000000000000000000000000000000003": { "builtin": { "name": "ripemd160", "pricing": { "linear": { "base": 600, "word": 120 } } } },
"0000000000000000000000000000000000000004": { "builtin": { "name": "identity", "pricing": { "linear": { "base": 15, "word": 3 } } } }
}
}

View File

@@ -26,9 +26,9 @@
"gasLimit": "0x1388"
},
"accounts": {
"0000000000000000000000000000000000000001": { "balance": "1", "builtin": { "name": "ecrecover", "linear": { "base": 3000, "word": 0 } } },
"0000000000000000000000000000000000000002": { "balance": "1", "builtin": { "name": "sha256", "linear": { "base": 60, "word": 12 } } },
"0000000000000000000000000000000000000003": { "balance": "1", "builtin": { "name": "ripemd160", "linear": { "base": 600, "word": 120 } } },
"0000000000000000000000000000000000000004": { "balance": "1", "builtin": { "name": "identity", "linear": { "base": 15, "word": 3 } } }
"0000000000000000000000000000000000000001": { "balance": "1", "builtin": { "name": "ecrecover", "pricing": { "linear": { "base": 3000, "word": 0 } } } },
"0000000000000000000000000000000000000002": { "balance": "1", "builtin": { "name": "sha256", "pricing": { "linear": { "base": 60, "word": 12 } } } },
"0000000000000000000000000000000000000003": { "balance": "1", "builtin": { "name": "ripemd160", "pricing": { "linear": { "base": 600, "word": 120 } } } },
"0000000000000000000000000000000000000004": { "balance": "1", "builtin": { "name": "identity", "pricing": { "linear": { "base": 15, "word": 3 } } } }
}
}

View File

@@ -29,10 +29,10 @@
"enode://b1217cbaa440e35ed471157123fe468e19e8b5ad5bedb4b1fdbcbdab6fb2f5ed3e95dd9c24a22a79fdb2352204cea207df27d92bfd21bfd41545e8b16f637499@104.44.138.37:30303"
],
"accounts": {
"0000000000000000000000000000000000000001": { "balance": "1", "nonce": "1048576", "builtin": { "name": "ecrecover", "linear": { "base": 3000, "word": 0 } } },
"0000000000000000000000000000000000000002": { "balance": "1", "nonce": "1048576", "builtin": { "name": "sha256", "linear": { "base": 60, "word": 12 } } },
"0000000000000000000000000000000000000003": { "balance": "1", "nonce": "1048576", "builtin": { "name": "ripemd160", "linear": { "base": 600, "word": 120 } } },
"0000000000000000000000000000000000000004": { "balance": "1", "nonce": "1048576", "builtin": { "name": "identity", "linear": { "base": 15, "word": 3 } } },
"0000000000000000000000000000000000000001": { "balance": "1", "nonce": "1048576", "builtin": { "name": "ecrecover", "pricing": { "linear": { "base": 3000, "word": 0 } } } },
"0000000000000000000000000000000000000002": { "balance": "1", "nonce": "1048576", "builtin": { "name": "sha256", "pricing": { "linear": { "base": 60, "word": 12 } } } },
"0000000000000000000000000000000000000003": { "balance": "1", "nonce": "1048576", "builtin": { "name": "ripemd160", "pricing": { "linear": { "base": 600, "word": 120 } } } },
"0000000000000000000000000000000000000004": { "balance": "1", "nonce": "1048576", "builtin": { "name": "identity", "pricing": { "linear": { "base": 15, "word": 3 } } } },
"102e61f5d8f9bc71d0ad4a084df4e65e05ce0e1c": { "balance": "1606938044258990275541962092341162602522202993782792835301376", "nonce": "1048576" }
}
}

View File

@@ -26,10 +26,10 @@
"gasLimit": "0x2fefd8"
},
"accounts": {
"0000000000000000000000000000000000000001": { "balance": "1", "builtin": { "name": "ecrecover", "linear": { "base": 3000, "word": 0 } } },
"0000000000000000000000000000000000000002": { "balance": "1", "builtin": { "name": "sha256", "linear": { "base": 60, "word": 12 } } },
"0000000000000000000000000000000000000003": { "balance": "1", "builtin": { "name": "ripemd160", "linear": { "base": 600, "word": 120 } } },
"0000000000000000000000000000000000000004": { "balance": "1", "builtin": { "name": "identity", "linear": { "base": 15, "word": 3 } } },
"0000000000000000000000000000000000000001": { "balance": "1", "builtin": { "name": "ecrecover", "pricing": { "linear": { "base": 3000, "word": 0 } } } },
"0000000000000000000000000000000000000002": { "balance": "1", "builtin": { "name": "sha256", "pricing": { "linear": { "base": 60, "word": 12 } } } },
"0000000000000000000000000000000000000003": { "balance": "1", "builtin": { "name": "ripemd160", "pricing": { "linear": { "base": 600, "word": 120 } } } },
"0000000000000000000000000000000000000004": { "balance": "1", "builtin": { "name": "identity", "pricing": { "linear": { "base": 15, "word": 3 } } } },
"dbdbdb2cbd23b783741e8d7fcf51e459b497e4a6": { "balance": "1606938044258990275541962092341162602522202993782792835301376" },
"e6716f9544a56c530d868e4bfbacb172315bdead": { "balance": "1606938044258990275541962092341162602522202993782792835301376" },
"b9c015918bdaba24b4ff057a92a3873d6eb201be": { "balance": "1606938044258990275541962092341162602522202993782792835301376" },

View File

@@ -26,10 +26,10 @@
"gasLimit": "0x2fefd8"
},
"accounts": {
"0000000000000000000000000000000000000001": { "balance": "1", "nonce": "1048576", "builtin": { "name": "ecrecover", "linear": { "base": 3000, "word": 0 } } },
"0000000000000000000000000000000000000002": { "balance": "1", "nonce": "1048576", "builtin": { "name": "sha256", "linear": { "base": 60, "word": 12 } } },
"0000000000000000000000000000000000000003": { "balance": "1", "nonce": "1048576", "builtin": { "name": "ripemd160", "linear": { "base": 600, "word": 120 } } },
"0000000000000000000000000000000000000004": { "balance": "1", "nonce": "1048576", "builtin": { "name": "identity", "linear": { "base": 15, "word": 3 } } },
"0000000000000000000000000000000000000001": { "balance": "1", "nonce": "1048576", "builtin": { "name": "ecrecover", "pricing": { "linear": { "base": 3000, "word": 0 } } } },
"0000000000000000000000000000000000000002": { "balance": "1", "nonce": "1048576", "builtin": { "name": "sha256", "pricing": { "linear": { "base": 60, "word": 12 } } } },
"0000000000000000000000000000000000000003": { "balance": "1", "nonce": "1048576", "builtin": { "name": "ripemd160", "pricing": { "linear": { "base": 600, "word": 120 } } } },
"0000000000000000000000000000000000000004": { "balance": "1", "nonce": "1048576", "builtin": { "name": "identity", "pricing": { "linear": { "base": 15, "word": 3 } } } },
"102e61f5d8f9bc71d0ad4a084df4e65e05ce0e1c": { "balance": "1606938044258990275541962092341162602522202993782792835301376", "nonce": "1048576" }
}
}

View File

@@ -138,7 +138,7 @@ impl Account {
/// get someone who knows to call `note_code`.
pub fn code(&self) -> Option<&[u8]> {
match self.code_hash {
Some(SHA3_EMPTY) | None if self.code_cache.is_empty() => Some(&self.code_cache),
Some(c) if c == SHA3_EMPTY && self.code_cache.is_empty() => Some(&self.code_cache),
Some(_) if !self.code_cache.is_empty() => Some(&self.code_cache),
None => Some(&self.code_cache),
_ => None,

View File

@@ -438,7 +438,7 @@ mod tests {
open_block.push_uncle(uncle1_header).unwrap();
open_block.push_uncle(uncle2_header).unwrap();
let b = open_block.close().seal(engine.deref(), vec![]).unwrap();
let orig_bytes = b.rlp_bytes();
let orig_db = b.drain();

View File

@@ -116,6 +116,7 @@ struct VerifyingBlock {
}
struct QueueSignal {
deleting: Arc<AtomicBool>,
signalled: AtomicBool,
message_channel: IoChannel<NetSyncMessage>,
}
@@ -123,10 +124,16 @@ struct QueueSignal {
impl QueueSignal {
#[cfg_attr(feature="dev", allow(bool_comparison))]
fn set(&self) {
// Do not signal when we are about to close
if self.deleting.load(AtomicOrdering::Relaxed) {
return;
}
if self.signalled.compare_and_swap(false, true, AtomicOrdering::Relaxed) == false {
self.message_channel.send(UserMessage(SyncMessage::BlockVerified)).expect("Error sending BlockVerified message");
}
}
fn reset(&self) {
self.signalled.store(false, AtomicOrdering::Relaxed);
}
@@ -150,8 +157,12 @@ impl BlockQueue {
bad: Mutex::new(HashSet::new()),
});
let more_to_verify = Arc::new(Condvar::new());
let ready_signal = Arc::new(QueueSignal { signalled: AtomicBool::new(false), message_channel: message_channel });
let deleting = Arc::new(AtomicBool::new(false));
let ready_signal = Arc::new(QueueSignal {
deleting: deleting.clone(),
signalled: AtomicBool::new(false),
message_channel: message_channel
});
let empty = Arc::new(Condvar::new());
let panic_handler = PanicHandler::new_in_arc();
@@ -431,12 +442,14 @@ impl MayPanic for BlockQueue {
impl Drop for BlockQueue {
fn drop(&mut self) {
trace!(target: "shutdown", "[BlockQueue] Closing...");
self.clear();
self.deleting.store(true, AtomicOrdering::Release);
self.more_to_verify.notify_all();
for t in self.verifiers.drain(..) {
t.join().unwrap();
}
trace!(target: "shutdown", "[BlockQueue] Closed.");
}
}

View File

@@ -100,6 +100,11 @@ pub trait BlockProvider {
self.block(&address.block_hash).and_then(|bytes| BlockView::new(&bytes).localized_transaction_at(address.index))
}
/// Get transaction receipt.
fn transaction_receipt(&self, address: &TransactionAddress) -> Option<Receipt> {
self.block_receipts(&address.block_hash).and_then(|br| br.receipts.into_iter().nth(address.index))
}
/// Get a list of transactions for a given block.
/// Returns None if block does not exist.
fn transactions(&self, hash: &H256) -> Option<Vec<LocalizedTransaction>> {

View File

@@ -19,7 +19,7 @@ use crypto::sha2::Sha256;
use crypto::ripemd160::Ripemd160;
use crypto::digest::Digest;
/// Definition of a contract whose implementation is built-in.
/// Definition of a contract whose implementation is built-in.
pub struct Builtin {
/// The gas cost of running this built-in for the given size of input data.
pub cost: Box<Fn(usize) -> U256>, // TODO: U256 should be bignum.
@@ -63,14 +63,16 @@ impl Builtin {
/// Create a builtin from JSON.
///
/// JSON must be of the form `{ "name": "identity", "linear": {"base": 10, "word": 20} }`.
/// JSON must be of the form `{ "name": "identity", "pricing": {"base": 10, "word": 20} }`.
pub fn from_json(json: &Json) -> Option<Builtin> {
// NICE: figure out a more convenient means of handing errors here.
if let Json::String(ref name) = json["name"] {
if let Json::Object(ref o) = json["linear"] {
if let Json::U64(ref word) = o["word"] {
if let Json::U64(ref base) = o["base"] {
return Self::from_named_linear(&name[..], *base as usize, *word as usize);
if let Json::Object(ref o) = json["pricing"] {
if let Json::Object(ref o) = o["linear"] {
if let Json::U64(ref word) = o["word"] {
if let Json::U64(ref base) = o["base"] {
return Self::from_named_linear(&name[..], *base as usize, *word as usize);
}
}
}
}
@@ -274,7 +276,7 @@ fn from_named_linear() {
#[test]
fn from_json() {
let text = "{ \"name\": \"identity\", \"linear\": {\"base\": 10, \"word\": 20} }";
let text = r#"{"name": "identity", "pricing": {"linear": {"base": 10, "word": 20}}}"#;
let json = Json::from_str(text).unwrap();
let b = Builtin::from_json(&json).unwrap();
assert_eq!((*b.cost)(0), U256::from(10));

View File

@@ -21,7 +21,7 @@ use util::*;
use util::panics::*;
use views::BlockView;
use error::*;
use header::{BlockNumber};
use header::{BlockNumber, Header};
use state::State;
use spec::Spec;
use engine::Engine;
@@ -30,13 +30,16 @@ use service::{NetSyncMessage, SyncMessage};
use env_info::LastHashes;
use verification::*;
use block::*;
use transaction::{LocalizedTransaction, SignedTransaction};
use transaction::{LocalizedTransaction, SignedTransaction, Action};
use extras::TransactionAddress;
use filter::Filter;
use log_entry::LocalizedLogEntry;
use block_queue::{BlockQueue, BlockQueueInfo};
use blockchain::{BlockChain, BlockProvider, TreeRoute, ImportRoute};
use client::{BlockId, TransactionId, ClientConfig, BlockChainClient};
use client::{BlockId, TransactionId, UncleId, ClientConfig, BlockChainClient};
use env_info::EnvInfo;
use executive::{Executive, Executed, TransactOptions, contract_address};
use receipt::LocalizedReceipt;
pub use blockchain::CacheSize as BlockChainCacheSize;
/// General block status
@@ -211,6 +214,7 @@ impl<V> Client<V> where V: Verifier {
let last_hashes = self.build_last_hashes(header.parent_hash.clone());
let db = self.state_db.lock().unwrap().spawn();
let enact_result = enact_verified(&block, engine, db, &parent, last_hashes);
if let Err(e) = enact_result {
warn!(target: "client", "Block import failed for #{} ({})\nError: {:?}", header.number(), header.hash(), e);
@@ -382,16 +386,51 @@ impl<V> Client<V> where V: Verifier {
BlockId::Latest => Some(self.chain.best_block_number())
}
}
fn transaction_address(&self, id: TransactionId) -> Option<TransactionAddress> {
match id {
TransactionId::Hash(ref hash) => self.chain.transaction_address(hash),
TransactionId::Location(id, index) => Self::block_hash(&self.chain, id).map(|hash| TransactionAddress {
block_hash: hash,
index: index
})
}
}
}
impl<V> BlockChainClient for Client<V> where V: Verifier {
fn call(&self, t: &SignedTransaction) -> Result<Executed, Error> {
let header = self.block_header(BlockId::Latest).unwrap();
let view = HeaderView::new(&header);
let last_hashes = self.build_last_hashes(view.hash());
let env_info = EnvInfo {
number: view.number(),
author: view.author(),
timestamp: view.timestamp(),
difficulty: view.difficulty(),
last_hashes: last_hashes,
gas_used: U256::zero(),
gas_limit: U256::max_value(),
};
// that's just a copy of the state.
let mut state = self.state();
let sender = try!(t.sender());
let balance = state.balance(&sender);
// give the sender max balance
state.sub_balance(&sender, &balance);
state.add_balance(&sender, &U256::max_value());
let options = TransactOptions { tracing: false, check_nonce: false };
Executive::new(&mut state, &env_info, self.engine.deref().deref()).transact(t, options)
}
// TODO [todr] Should be moved to miner crate eventually.
fn try_seal(&self, block: ClosedBlock, seal: Vec<Bytes>) -> Result<SealedBlock, ClosedBlock> {
block.try_seal(self.engine.deref().deref(), seal)
}
// TODO [todr] Should be moved to miner crate eventually.
fn prepare_sealing(&self, author: Address, gas_floor_target: U256, extra_data: Bytes, transactions: Vec<SignedTransaction>) -> Option<ClosedBlock> {
fn prepare_sealing(&self, author: Address, gas_floor_target: U256, extra_data: Bytes, transactions: Vec<SignedTransaction>)
-> Option<(ClosedBlock, HashSet<H256>)> {
let engine = self.engine.deref().deref();
let h = self.chain.best_block_hash();
@@ -417,21 +456,40 @@ impl<V> BlockChainClient for Client<V> where V: Verifier {
// Add transactions
let block_number = b.block().header().number();
let min_tx_gas = U256::from(self.engine.schedule(&b.env_info()).tx_gas);
let mut invalid_transactions = HashSet::new();
for tx in transactions {
// Push transaction to block
let hash = tx.hash();
let import = b.push_transaction(tx, None);
if let Err(e) = import {
trace!("Error adding transaction to block: number={}. Error: {:?}", block_number, e);
match import {
Err(Error::Execution(ExecutionError::BlockGasLimitReached { gas_limit, gas_used, .. })) => {
trace!(target: "miner", "Skipping adding transaction to block because of gas limit: {:?}", hash);
// Exit early if gas left is smaller then min_tx_gas
if gas_limit - gas_used < min_tx_gas {
break;
}
},
Err(e) => {
invalid_transactions.insert(hash);
trace!(target: "miner",
"Error adding transaction to block: number={}. transaction_hash={:?}, Error: {:?}",
block_number, hash, e);
},
_ => {}
}
}
// And close
let b = b.close();
trace!("Sealing: number={}, hash={}, diff={}",
trace!(target: "miner", "Sealing: number={}, hash={}, diff={}",
b.block().header().number(),
b.hash(),
b.block().header().difficulty()
);
Some(b)
Some((b, invalid_transactions))
}
fn block_header(&self, id: BlockId) -> Option<Bytes> {
@@ -489,13 +547,50 @@ impl<V> BlockChainClient for Client<V> where V: Verifier {
}
fn transaction(&self, id: TransactionId) -> Option<LocalizedTransaction> {
match id {
TransactionId::Hash(ref hash) => self.chain.transaction_address(hash),
TransactionId::Location(id, index) => Self::block_hash(&self.chain, id).map(|hash| TransactionAddress {
block_hash: hash,
index: index
})
}.and_then(|address| self.chain.transaction(&address))
self.transaction_address(id).and_then(|address| self.chain.transaction(&address))
}
fn uncle(&self, id: UncleId) -> Option<Header> {
let index = id.1;
self.block(id.0).and_then(|block| BlockView::new(&block).uncle_at(index))
}
fn transaction_receipt(&self, id: TransactionId) -> Option<LocalizedReceipt> {
self.transaction_address(id).and_then(|address| {
let t = self.chain.block(&address.block_hash)
.and_then(|block| BlockView::new(&block).localized_transaction_at(address.index));
match (t, self.chain.transaction_receipt(&address)) {
(Some(tx), Some(receipt)) => {
let block_hash = tx.block_hash.clone();
let block_number = tx.block_number.clone();
let transaction_hash = tx.hash();
let transaction_index = tx.transaction_index;
Some(LocalizedReceipt {
transaction_hash: tx.hash(),
transaction_index: tx.transaction_index,
block_hash: tx.block_hash,
block_number: tx.block_number,
// TODO: to fix this, query all previous transaction receipts and retrieve their gas usage
cumulative_gas_used: receipt.gas_used,
gas_used: receipt.gas_used,
contract_address: match tx.action {
Action::Call(_) => None,
Action::Create => Some(contract_address(&tx.sender().unwrap(), &tx.nonce))
},
logs: receipt.logs.into_iter().enumerate().map(|(i, log)| LocalizedLogEntry {
entry: log,
block_hash: block_hash.clone(),
block_number: block_number,
transaction_hash: transaction_hash.clone(),
transaction_index: transaction_index,
log_index: i
}).collect()
})
},
_ => None
}
})
}
fn tree_route(&self, from: &H256, to: &H256) -> Option<TreeRoute> {
@@ -580,7 +675,7 @@ impl<V> BlockChainClient for Client<V> where V: Verifier {
.map(|(i, log)| LocalizedLogEntry {
entry: log,
block_hash: hash.clone(),
block_number: number as usize,
block_number: number,
transaction_hash: hashes.get(index).cloned().unwrap_or_else(H256::new),
transaction_index: index,
log_index: log_index + i

View File

@@ -20,7 +20,7 @@ use util::hash::H256;
use header::BlockNumber;
/// Uniquely identifies block.
#[derive(Debug, PartialEq, Clone)]
#[derive(Debug, PartialEq, Clone, Hash, Eq)]
pub enum BlockId {
/// Block's sha3.
/// Querying by hash is always faster.
@@ -34,7 +34,7 @@ pub enum BlockId {
}
/// Uniquely identifies transaction.
#[derive(Debug, PartialEq, Clone)]
#[derive(Debug, PartialEq, Clone, Hash, Eq)]
pub enum TransactionId {
/// Transaction's sha3.
Hash(H256),
@@ -42,3 +42,11 @@ pub enum TransactionId {
/// Querying by block position is always faster.
Location(BlockId, usize)
}
/// Uniquely identifies Uncle.
pub struct UncleId (
/// Block id.
pub BlockId,
/// Position in block.
pub usize
);

View File

@@ -23,20 +23,23 @@ mod test_client;
pub use self::client::*;
pub use self::config::{ClientConfig, BlockQueueConfig, BlockChainConfig};
pub use self::ids::{BlockId, TransactionId};
pub use self::ids::{BlockId, TransactionId, UncleId};
pub use self::test_client::{TestBlockChainClient, EachBlockWith};
pub use executive::Executed;
use std::collections::HashSet;
use util::bytes::Bytes;
use util::hash::{Address, H256, H2048};
use util::numbers::U256;
use blockchain::TreeRoute;
use block_queue::BlockQueueInfo;
use block::{ClosedBlock, SealedBlock};
use header::BlockNumber;
use header::{BlockNumber, Header};
use transaction::{LocalizedTransaction, SignedTransaction};
use log_entry::LocalizedLogEntry;
use filter::Filter;
use error::{ImportResult};
use error::{ImportResult, Error};
use receipt::LocalizedReceipt;
/// Blockchain database client. Owns and manages a blockchain and a block queue.
pub trait BlockChainClient : Sync + Send {
@@ -74,6 +77,12 @@ pub trait BlockChainClient : Sync + Send {
/// Get transaction with given hash.
fn transaction(&self, id: TransactionId) -> Option<LocalizedTransaction>;
/// Get uncle with given id.
fn uncle(&self, id: UncleId) -> Option<Header>;
/// Get transaction receipt with given hash.
fn transaction_receipt(&self, id: TransactionId) -> Option<LocalizedReceipt>;
/// Get a tree route between `from` and `to`.
/// See `BlockChain::tree_route`.
fn tree_route(&self, from: &H256, to: &H256) -> Option<TreeRoute>;
@@ -110,11 +119,14 @@ pub trait BlockChainClient : Sync + Send {
// TODO [todr] Should be moved to miner crate eventually.
/// Returns ClosedBlock prepared for sealing.
fn prepare_sealing(&self, author: Address, gas_floor_target: U256, extra_data: Bytes, transactions: Vec<SignedTransaction>) -> Option<ClosedBlock>;
fn prepare_sealing(&self, author: Address, gas_floor_target: U256, extra_data: Bytes, transactions: Vec<SignedTransaction>)
-> Option<(ClosedBlock, HashSet<H256>)>;
// TODO [todr] Should be moved to miner crate eventually.
/// Attempts to seal given block. Returns `SealedBlock` on success and the same block in case of error.
fn try_seal(&self, block: ClosedBlock, seal: Vec<Bytes>) -> Result<SealedBlock, ClosedBlock>;
/// Makes a non-persistent transaction call.
fn call(&self, t: &SignedTransaction) -> Result<Executed, Error>;
}

View File

@@ -16,19 +16,22 @@
//! Test client.
use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrder};
use util::*;
use transaction::{Transaction, LocalizedTransaction, SignedTransaction, Action};
use blockchain::TreeRoute;
use client::{BlockChainClient, BlockChainInfo, BlockStatus, BlockId, TransactionId};
use client::{BlockChainClient, BlockChainInfo, BlockStatus, BlockId, TransactionId, UncleId};
use header::{Header as BlockHeader, BlockNumber};
use filter::Filter;
use log_entry::LocalizedLogEntry;
use receipt::Receipt;
use receipt::{Receipt, LocalizedReceipt};
use extras::BlockReceipts;
use error::{ImportResult};
use block_queue::BlockQueueInfo;
use block::{SealedBlock, ClosedBlock};
use executive::Executed;
use error::Error;
/// Test client.
pub struct TestBlockChainClient {
@@ -48,6 +51,12 @@ pub struct TestBlockChainClient {
pub storage: RwLock<HashMap<(Address, H256), H256>>,
/// Code.
pub code: RwLock<HashMap<Address, Bytes>>,
/// Execution result.
pub execution_result: RwLock<Option<Executed>>,
/// Transaction receipts.
pub receipts: RwLock<HashMap<TransactionId, LocalizedReceipt>>,
/// Block queue size.
pub queue_size: AtomicUsize,
}
#[derive(Clone)]
@@ -82,12 +91,25 @@ impl TestBlockChainClient {
balances: RwLock::new(HashMap::new()),
storage: RwLock::new(HashMap::new()),
code: RwLock::new(HashMap::new()),
execution_result: RwLock::new(None),
receipts: RwLock::new(HashMap::new()),
queue_size: AtomicUsize::new(0),
};
client.add_blocks(1, EachBlockWith::Nothing); // add genesis block
client.genesis_hash = client.last_hash.read().unwrap().clone();
client
}
/// Set the transaction receipt result
pub fn set_transaction_receipt(&self, id: TransactionId, receipt: LocalizedReceipt) {
self.receipts.write().unwrap().insert(id, receipt);
}
/// Set the execution result.
pub fn set_execution_result(&self, result: Executed) {
*self.execution_result.write().unwrap() = Some(result);
}
/// Set the balance of account `address` to `balance`.
pub fn set_balance(&self, address: Address, balance: U256) {
self.balances.write().unwrap().insert(address, balance);
@@ -103,6 +125,11 @@ impl TestBlockChainClient {
self.storage.write().unwrap().insert((address, position), value);
}
/// Set block queue size for testing
pub fn set_queue_size(&self, size: usize) {
self.queue_size.store(size, AtomicOrder::Relaxed);
}
/// Add blocks to test client.
pub fn add_blocks(&self, count: usize, with: EachBlockWith) {
let len = self.numbers.read().unwrap().len();
@@ -111,6 +138,7 @@ impl TestBlockChainClient {
header.difficulty = From::from(n);
header.parent_hash = self.last_hash.read().unwrap().clone();
header.number = n as BlockNumber;
header.gas_limit = U256::from(1_000_000);
let uncles = match with {
EachBlockWith::Uncle | EachBlockWith::UncleAndTransaction => {
let mut uncles = RlpStream::new_list(1);
@@ -181,6 +209,10 @@ impl TestBlockChainClient {
}
impl BlockChainClient for TestBlockChainClient {
fn call(&self, _t: &SignedTransaction) -> Result<Executed, Error> {
Ok(self.execution_result.read().unwrap().clone().unwrap())
}
fn block_total_difficulty(&self, _id: BlockId) -> Option<U256> {
Some(U256::zero())
}
@@ -209,6 +241,14 @@ impl BlockChainClient for TestBlockChainClient {
unimplemented!();
}
fn uncle(&self, _id: UncleId) -> Option<BlockHeader> {
unimplemented!();
}
fn transaction_receipt(&self, id: TransactionId) -> Option<LocalizedReceipt> {
self.receipts.read().unwrap().get(&id).cloned()
}
fn blocks_with_bloom(&self, _bloom: &H2048, _from_block: BlockId, _to_block: BlockId) -> Option<Vec<BlockNumber>> {
unimplemented!();
}
@@ -217,12 +257,12 @@ impl BlockChainClient for TestBlockChainClient {
unimplemented!();
}
fn prepare_sealing(&self, _author: Address, _gas_floor_target: U256, _extra_data: Bytes, _transactions: Vec<SignedTransaction>) -> Option<ClosedBlock> {
unimplemented!()
fn prepare_sealing(&self, _author: Address, _gas_floor_target: U256, _extra_data: Bytes, _transactions: Vec<SignedTransaction>) -> Option<(ClosedBlock, HashSet<H256>)> {
None
}
fn try_seal(&self, _block: ClosedBlock, _seal: Vec<Bytes>) -> Result<SealedBlock, ClosedBlock> {
unimplemented!()
fn try_seal(&self, block: ClosedBlock, _seal: Vec<Bytes>) -> Result<SealedBlock, ClosedBlock> {
Err(block)
}
fn block_header(&self, id: BlockId) -> Option<Bytes> {
@@ -352,7 +392,7 @@ impl BlockChainClient for TestBlockChainClient {
fn queue_info(&self) -> BlockQueueInfo {
BlockQueueInfo {
verified_queue_size: 0,
verified_queue_size: self.queue_size.load(AtomicOrder::Relaxed),
unverified_queue_size: 0,
verifying_queue_size: 0,
max_queue_size: 0,

View File

@@ -65,12 +65,30 @@ pub enum ExecutionError {
#[derive(Debug)]
/// Errors concerning transaction processing.
pub enum TransactionError {
/// Transaction is already imported to the queue
AlreadyImported,
/// Transaction is not valid anymore (state already has higher nonce)
Old,
/// Transaction's gas price is below threshold.
InsufficientGasPrice {
/// Minimal expected gas price
minimal: U256,
/// Transaction gas price
got: U256
got: U256,
},
/// Sender doesn't have enough funds to pay for this transaction
InsufficientBalance {
/// Senders balance
balance: U256,
/// Transaction cost
cost: U256,
},
/// Transactions gas is higher then current gas limit
GasLimitExceeded {
/// Current gas limit
limit: U256,
/// Declared transaction gas
got: U256,
},
/// Transaction's gas limit (aka gas) is invalid.
InvalidGasLimit(OutOfBounds<U256>),

View File

@@ -67,6 +67,7 @@ pub trait Ext {
/// Returns Err, if we run out of gas.
/// Otherwise returns call_result which contains gas left
/// and true if subcall was successfull.
#[cfg_attr(feature="dev", allow(too_many_arguments))]
fn call(&mut self,
gas: &U256,
sender_address: &Address,

View File

@@ -521,6 +521,7 @@ impl Interpreter {
Ok(overflowing!(offset.overflowing_add(size.clone())))
}
#[cfg_attr(feature="dev", allow(too_many_arguments))]
fn exec_instruction(&self,
gas: Gas,
params: &ActionParams,

View File

@@ -36,8 +36,16 @@ pub fn contract_address(address: &Address, nonce: &U256) -> Address {
From::from(stream.out().sha3())
}
/// Transaction execution options.
pub struct TransactOptions {
/// Enable call tracing.
pub tracing: bool,
/// Check transaction nonce before execution.
pub check_nonce: bool,
}
/// Transaction execution receipt.
#[derive(Debug)]
#[derive(Debug, PartialEq, Clone)]
pub struct Executed {
/// Gas paid up front for execution of transaction.
pub gas: U256,
@@ -60,7 +68,9 @@ pub struct Executed {
/// eg. sender creates contract A and A in constructor creates contract B
///
/// B creation ends first, and it will be the first element of the vector.
pub contracts_created: Vec<Address>
pub contracts_created: Vec<Address>,
/// Transaction output.
pub output: Bytes,
}
/// Transaction execution result.
@@ -102,7 +112,7 @@ impl<'a> Executive<'a> {
}
/// This funtion should be used to execute transaction.
pub fn transact(&'a mut self, t: &SignedTransaction) -> Result<Executed, Error> {
pub fn transact(&'a mut self, t: &SignedTransaction, options: TransactOptions) -> Result<Executed, Error> {
let sender = try!(t.sender());
let nonce = self.state.nonce(&sender);
@@ -116,8 +126,10 @@ impl<'a> Executive<'a> {
let init_gas = t.gas - base_gas_required;
// validate transaction nonce
if t.nonce != nonce {
return Err(From::from(ExecutionError::InvalidNonce { expected: nonce, got: t.nonce }));
if options.check_nonce {
if t.nonce != nonce {
return Err(From::from(ExecutionError::InvalidNonce { expected: nonce, got: t.nonce }));
}
}
// validate if transaction fits into given block
@@ -145,7 +157,7 @@ impl<'a> Executive<'a> {
let mut substate = Substate::new();
let res = match t.action {
let (gas_left, output) = match t.action {
Action::Create => {
let new_address = contract_address(&sender, &nonce);
let params = ActionParams {
@@ -159,7 +171,7 @@ impl<'a> Executive<'a> {
code: Some(t.data.clone()),
data: None,
};
self.create(params, &mut substate)
(self.create(params, &mut substate), vec![])
},
Action::Call(ref address) => {
let params = ActionParams {
@@ -175,12 +187,12 @@ impl<'a> Executive<'a> {
};
// TODO: move output upstream
let mut out = vec![];
self.call(params, &mut substate, BytesRef::Flexible(&mut out))
(self.call(params, &mut substate, BytesRef::Flexible(&mut out)), out)
}
};
// finalize here!
Ok(try!(self.finalize(t, substate, res)))
Ok(try!(self.finalize(t, substate, gas_left, output)))
}
fn exec_vm(&mut self, params: ActionParams, unconfirmed_substate: &mut Substate, output_policy: OutputPolicy) -> evm::Result {
@@ -286,7 +298,7 @@ impl<'a> Executive<'a> {
}
/// Finalizes the transaction (does refunds and suicides).
fn finalize(&mut self, t: &SignedTransaction, substate: Substate, result: evm::Result) -> ExecutionResult {
fn finalize(&mut self, t: &SignedTransaction, substate: Substate, result: evm::Result, output: Bytes) -> ExecutionResult {
let schedule = self.engine.schedule(self.info);
// refunds from SSTORE nonzero -> zero
@@ -326,7 +338,8 @@ impl<'a> Executive<'a> {
refunded: U256::zero(),
cumulative_gas_used: self.info.gas_used + t.gas,
logs: vec![],
contracts_created: vec![]
contracts_created: vec![],
output: output,
})
},
_ => {
@@ -337,6 +350,7 @@ impl<'a> Executive<'a> {
cumulative_gas_used: self.info.gas_used + gas_used,
logs: substate.logs,
contracts_created: substate.contracts_created,
output: output,
})
},
}
@@ -699,7 +713,8 @@ mod tests {
let executed = {
let mut ex = Executive::new(&mut state, &info, &engine);
ex.transact(&t).unwrap()
let opts = TransactOptions { check_nonce: true, tracing: false };
ex.transact(&t, opts).unwrap()
};
assert_eq!(executed.gas, U256::from(100_000));
@@ -723,7 +738,7 @@ mod tests {
gas: U256::from(100_000),
gas_price: U256::zero(),
nonce: U256::zero()
}.fake_sign();
}.invalid_sign();
let mut state_result = get_temp_state();
let mut state = state_result.reference_mut();
let mut info = EnvInfo::default();
@@ -732,7 +747,8 @@ mod tests {
let res = {
let mut ex = Executive::new(&mut state, &info, &engine);
ex.transact(&t)
let opts = TransactOptions { check_nonce: true, tracing: false };
ex.transact(&t, opts)
};
match res {
@@ -763,7 +779,8 @@ mod tests {
let res = {
let mut ex = Executive::new(&mut state, &info, &engine);
ex.transact(&t)
let opts = TransactOptions { check_nonce: true, tracing: false };
ex.transact(&t, opts)
};
match res {
@@ -796,7 +813,8 @@ mod tests {
let res = {
let mut ex = Executive::new(&mut state, &info, &engine);
ex.transact(&t)
let opts = TransactOptions { check_nonce: true, tracing: false };
ex.transact(&t, opts)
};
match res {
@@ -829,7 +847,8 @@ mod tests {
let res = {
let mut ex = Executive::new(&mut state, &info, &engine);
ex.transact(&t)
let opts = TransactOptions { check_nonce: true, tracing: false };
ex.transact(&t, opts)
};
match res {

View File

@@ -16,18 +16,19 @@
use super::test_common::*;
use client::{BlockChainClient, Client, ClientConfig};
use pod_state::*;
use block::Block;
use ethereum;
use tests::helpers::*;
use devtools::*;
use spec::Genesis;
use ethjson;
pub fn json_chain_test(json_data: &[u8], era: ChainEra) -> Vec<String> {
init_log();
let json = Json::from_str(::std::str::from_utf8(json_data).unwrap()).expect("Json is invalid");
let tests = ethjson::blockchain::Test::load(json_data).unwrap();
let mut failed = Vec::new();
for (name, test) in json.as_object().unwrap() {
for (name, blockchain) in tests.deref() {
let mut fail = false;
{
let mut fail_unless = |cond: bool| if !cond && !fail {
@@ -39,37 +40,36 @@ pub fn json_chain_test(json_data: &[u8], era: ChainEra) -> Vec<String> {
flush!(" - {}...", name);
let blocks: Vec<(Bytes, bool)> = test["blocks"].as_array().unwrap().iter().map(|e| (xjson!(&e["rlp"]), e.find("blockHeader").is_some())).collect();
let mut spec = match era {
ChainEra::Frontier => ethereum::new_frontier_test(),
ChainEra::Homestead => ethereum::new_homestead_test(),
};
let s = PodState::from_json(test.find("pre").unwrap());
spec.set_genesis_state(s);
spec.overwrite_genesis(test.find("genesisBlockHeader").unwrap());
let genesis = Genesis::from(blockchain.genesis());
let state = From::from(blockchain.pre_state.clone());
spec.set_genesis_state(state);
spec.overwrite_genesis_params(genesis);
assert!(spec.is_state_root_valid());
let genesis_hash = spec.genesis_header().hash();
assert_eq!(genesis_hash, H256::from_json(&test.find("genesisBlockHeader").unwrap()["hash"]));
let temp = RandomTempPath::new();
{
let client = Client::new(ClientConfig::default(), spec, temp.as_path(), IoChannel::disconnected()).unwrap();
assert_eq!(client.chain_info().best_block_hash, genesis_hash);
for (b, is_valid) in blocks.into_iter() {
for b in &blockchain.blocks_rlp() {
if Block::is_good(&b) {
let _ = client.import_block(b.clone());
client.flush_queue();
client.import_verified_blocks(&IoChannel::disconnected());
}
client.flush_queue();
let imported_ok = client.import_verified_blocks(&IoChannel::disconnected()) > 0;
assert_eq!(imported_ok, is_valid);
}
fail_unless(client.chain_info().best_block_hash == H256::from_json(&test["lastblockhash"]));
fail_unless(client.chain_info().best_block_hash == blockchain.best_block.clone().into());
}
}
if !fail {
flushln!("ok");
}
}
println!("!!! {:?} tests from failed.", failed.len());
failed
}

View File

@@ -83,6 +83,7 @@ extern crate time;
extern crate env_logger;
extern crate num_cpus;
extern crate crossbeam;
extern crate ethjson;
#[cfg(test)] extern crate ethcore_devtools as devtools;
#[cfg(feature = "jit" )] extern crate evmjit;
@@ -100,13 +101,13 @@ pub mod spec;
pub mod transaction;
pub mod views;
pub mod receipt;
pub mod pod_state;
mod common;
mod basic_types;
#[macro_use] mod evm;
mod env_info;
mod pod_account;
mod pod_state;
mod account_diff;
mod state_diff;
mod engine;

View File

@@ -18,6 +18,7 @@
use util::*;
use basic_types::LogBloom;
use header::BlockNumber;
/// A record of execution for a `LOG` operation.
#[derive(Default, Debug, Clone, PartialEq, Eq)]
@@ -77,14 +78,14 @@ impl FromJson for LogEntry {
}
/// Log localized in a blockchain.
#[derive(Default, Debug, PartialEq)]
#[derive(Default, Debug, PartialEq, Clone)]
pub struct LocalizedLogEntry {
/// Plain log entry.
pub entry: LogEntry,
/// Block in which this log was created.
pub block_hash: H256,
/// Block number.
pub block_number: usize,
pub block_number: BlockNumber,
/// Hash of transaction in which this log was created.
pub transaction_hash: H256,
/// Index of transaction within block.

View File

@@ -17,6 +17,7 @@
use util::*;
use account::*;
use account_db::*;
use ethjson;
#[derive(Debug,Clone,PartialEq,Eq)]
/// An account, expressed as Plain-Old-Data (hence the name).
@@ -73,6 +74,22 @@ impl PodAccount {
}
}
impl From<ethjson::blockchain::Account> for PodAccount {
fn from(a: ethjson::blockchain::Account) -> Self {
PodAccount {
balance: a.balance.into(),
nonce: a.nonce.into(),
code: a.code.into(),
storage: a.storage.into_iter().fold(BTreeMap::new(), |mut acc, (key, value)| {
let key: U256 = key.into();
let value: U256 = value.into();
acc.insert(H256::from(key), H256::from(value));
acc
})
}
}
}
impl fmt::Display for PodAccount {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "(bal={}; nonce={}; code={} bytes, #{}; storage={} items)", self.balance, self.nonce, self.code.len(), self.code.sha3(), self.storage.len())

View File

@@ -14,11 +14,14 @@
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! State of all accounts in the system expressed in Plain Old Data.
use util::*;
use pod_account::*;
use ethjson;
#[derive(Debug,Clone,PartialEq,Eq,Default)]
/// State of all accounts in the system expressed in Plain Old Data.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct PodState (BTreeMap<Address, PodAccount>);
impl PodState {
@@ -64,6 +67,15 @@ impl FromJson for PodState {
}
}
impl From<ethjson::blockchain::State> for PodState {
fn from(s: ethjson::blockchain::State) -> PodState {
PodState(s.0.into_iter().fold(BTreeMap::new(), |mut acc, (key, value)| {
acc.insert(key.into(), PodAccount::from(value));
acc
}))
}
}
impl fmt::Display for PodState {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for (add, acc) in &self.0 {

View File

@@ -18,7 +18,8 @@
use util::*;
use basic_types::LogBloom;
use log_entry::LogEntry;
use header::BlockNumber;
use log_entry::{LogEntry, LocalizedLogEntry};
/// Information describing execution of a transaction.
#[derive(Default, Debug, Clone)]
@@ -74,6 +75,27 @@ impl HeapSizeOf for Receipt {
}
}
/// Receipt with additional info.
#[derive(Debug, Clone, PartialEq)]
pub struct LocalizedReceipt {
/// Transaction hash.
pub transaction_hash: H256,
/// Transaction index.
pub transaction_index: usize,
/// Block hash.
pub block_hash: H256,
/// Block number.
pub block_number: BlockNumber,
/// Cumulative gas used.
pub cumulative_gas_used: U256,
/// Gas used.
pub gas_used: U256,
/// Contract address.
pub contract_address: Option<Address>,
/// Logs
pub logs: Vec<LocalizedLogEntry>,
}
#[test]
fn test_basic() {
let expected = FromHex::from_hex("f90162a02f697d671e9ae4ee24a43c4b0d7e15f1cb4ba6de1561120d43b9a4e8c4a8a6ee83040caeb9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000f838f794dcf421d093428b096ca501a7cd1a740855a7976fc0a00000000000000000000000000000000000000000000000000000000000000000").unwrap();

View File

@@ -0,0 +1,91 @@
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use util::rlp::*;
use util::numbers::{Uint, U256};
use util::hash::{H64, Address, H256};
use ethjson;
/// Genesis seal type.
pub enum Seal {
/// Classic ethereum seal.
Ethereum {
/// Seal nonce.
nonce: H64,
/// Seal mix hash.
mix_hash: H256,
},
/// Generic seal.
Generic {
/// Number of seal fields.
fields: usize,
/// Seal rlp.
rlp: Vec<u8>,
},
}
/// Genesis components.
pub struct Genesis {
/// Seal.
pub seal: Seal,
/// Difficulty.
pub difficulty: U256,
/// Author.
pub author: Address,
/// Timestamp.
pub timestamp: u64,
/// Parent hash.
pub parent_hash: H256,
/// Gas limit.
pub gas_limit: U256,
/// Transactions root.
pub transactions_root: H256,
/// Receipts root.
pub receipts_root: H256,
/// State root.
pub state_root: Option<H256>,
/// Gas used.
pub gas_used: U256,
/// Extra data.
pub extra_data: Vec<u8>,
}
impl From<ethjson::spec::Genesis> for Genesis {
fn from(g: ethjson::spec::Genesis) -> Self {
Genesis {
seal: match (g.nonce, g.mix_hash) {
(Some(nonce), Some(mix_hash)) => Seal::Ethereum {
nonce: nonce.into(),
mix_hash: mix_hash.into(),
},
_ => Seal::Generic {
fields: g.seal_fields.unwrap(),
rlp: g.seal_rlp.unwrap().into(),
}
},
difficulty: g.difficulty.into(),
author: g.author.into(),
timestamp: g.timestamp.into(),
parent_hash: g.parent_hash.into(),
gas_limit: g.gas_limit.into(),
transactions_root: g.transactions_root.map_or_else(|| SHA3_NULL_RLP.clone(), Into::into),
receipts_root: g.receipts_root.map_or_else(|| SHA3_NULL_RLP.clone(), Into::into),
state_root: g.state_root.map(Into::into),
gas_used: g.gas_used.map_or_else(U256::zero, Into::into),
extra_data: g.extra_data.map_or_else(Vec::new, Into::into),
}
}
}

23
ethcore/src/spec/mod.rs Normal file
View File

@@ -0,0 +1,23 @@
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Blockchain params.
mod genesis;
pub mod spec;
pub use self::spec::*;
pub use self::genesis::Genesis;

View File

@@ -21,6 +21,8 @@ use engine::*;
use pod_state::*;
use null_engine::*;
use account_db::*;
use ethereum;
use super::genesis::{Seal as GenesisSeal, Genesis};
/// Convert JSON value to equivalent RLP representation.
// TODO: handle container types.
@@ -106,7 +108,7 @@ impl Spec {
pub fn to_engine(self) -> Result<Box<Engine>, Error> {
match self.engine_name.as_ref() {
"NullEngine" => Ok(NullEngine::new_boxed(self)),
"Ethash" => Ok(super::ethereum::Ethash::new_boxed(self)),
"Ethash" => Ok(ethereum::Ethash::new_boxed(self)),
_ => Err(Error::UnknownEngineName(self.engine_name.clone()))
}
}
@@ -197,6 +199,32 @@ impl Spec {
self.state_root_memo = RwLock::new(genesis.find("stateRoot").and_then(|_| Some(H256::from_json(&genesis["stateRoot"]))));
}
/// Overwrite the genesis components.
pub fn overwrite_genesis_params(&mut self, g: Genesis) {
let (seal_fields, seal_rlp) = match g.seal {
GenesisSeal::Generic { fields, rlp } => (fields, rlp),
GenesisSeal::Ethereum { nonce, mix_hash } => {
let mut s = RlpStream::new();
s.append(&mix_hash);
s.append(&nonce);
(2, s.out())
}
};
self.parent_hash = g.parent_hash;
self.transactions_root = g.transactions_root;
self.receipts_root = g.receipts_root;
self.author = g.author;
self.difficulty = g.difficulty;
self.gas_limit = g.gas_limit;
self.gas_used = g.gas_used;
self.timestamp = g.timestamp;
self.extra_data = g.extra_data;
self.seal_fields = seal_fields;
self.seal_rlp = seal_rlp;
self.state_root_memo = RwLock::new(g.state_root);
}
/// Alter the value of the genesis state.
pub fn set_genesis_state(&mut self, s: PodState) {
self.genesis_state = s;
@@ -304,7 +332,7 @@ impl Spec {
}
/// Create a new Spec which conforms to the Morden chain except that it's a NullEngine consensus.
pub fn new_test() -> Spec { Self::from_json_utf8(include_bytes!("../res/null_morden.json")) }
pub fn new_test() -> Spec { Self::from_json_utf8(include_bytes!("../../res/null_morden.json")) }
}
#[cfg(test)]

View File

@@ -16,7 +16,7 @@
use common::*;
use engine::Engine;
use executive::Executive;
use executive::{Executive, TransactOptions};
use account_db::*;
#[cfg(test)]
#[cfg(feature = "json-tests")]
@@ -212,7 +212,8 @@ impl State {
pub fn apply(&mut self, env_info: &EnvInfo, engine: &Engine, t: &SignedTransaction) -> ApplyResult {
// let old = self.to_pod();
let e = try!(Executive::new(self, env_info, engine).transact(t));
let options = TransactOptions { tracing: false, check_nonce: true };
let e = try!(Executive::new(self, env_info, engine).transact(t, options));
// TODO uncomment once to_pod() works correctly.
// trace!("Applied transaction. Diff:\n{}\n", StateDiff::diff_pod(&old, &self.to_pod()));

View File

@@ -144,7 +144,7 @@ fn can_mine() {
let client_result = get_test_client_with_blocks(vec![dummy_blocks[0].clone()]);
let client = client_result.reference();
let b = client.prepare_sealing(Address::default(), x!(31415926), vec![], vec![]).unwrap();
let b = client.prepare_sealing(Address::default(), x!(31415926), vec![], vec![]).unwrap().0;
assert_eq!(*b.block().header().parent_hash(), BlockView::new(&dummy_blocks[0]).header_view().sha3());
assert!(client.try_seal(b, vec![]).is_ok());

View File

@@ -134,7 +134,7 @@ impl Transaction {
/// Useful for test incorrectly signed transactions.
#[cfg(test)]
pub fn fake_sign(self) -> SignedTransaction {
pub fn invalid_sign(self) -> SignedTransaction {
SignedTransaction {
unsigned: self,
r: U256::zero(),
@@ -145,6 +145,18 @@ impl Transaction {
}
}
/// Specify the sender; this won't survive the serialize/deserialize process, but can be cloned.
pub fn fake_sign(self, from: Address) -> SignedTransaction {
SignedTransaction {
unsigned: self,
r: U256::zero(),
s: U256::zero(),
v: 0,
hash: Cell::new(None),
sender: Cell::new(Some(from)),
}
}
/// Get the transaction cost in gas for the given params.
pub fn gas_required_for(is_create: bool, data: &[u8], schedule: &Schedule) -> u64 {
data.iter().fold(
@@ -342,3 +354,19 @@ fn signing() {
}.sign(&key.secret());
assert_eq!(Address::from(key.public().sha3()), t.sender().unwrap());
}
#[test]
fn fake_signing() {
let t = Transaction {
action: Action::Create,
nonce: U256::from(42),
gas_price: U256::from(3000),
gas: U256::from(50_000),
value: U256::from(1),
data: b"Hello!".to_vec()
}.fake_sign(Address::from(0x69));
assert_eq!(Address::from(0x69), t.sender().unwrap());
let t = t.clone();
assert_eq!(Address::from(0x69), t.sender().unwrap());
}

View File

@@ -256,6 +256,9 @@ impl<'a> HeaderView<'a> {
}
}
/// Returns header hash.
pub fn hash(&self) -> H256 { self.sha3() }
/// Returns raw rlp.
pub fn rlp(&self) -> &Rlp<'a> { &self.rlp }

View File

@@ -1,6 +1,6 @@
[package]
name = "evmjit"
version = "1.1.0"
version = "1.0.0"
authors = ["debris <marek.kotewicz@gmail.com>"]
[lib]

View File

@@ -1,6 +1,6 @@
#!/usr/bin/env bash
PARITY_DEB_URL=https://github.com/ethcore/parity/releases/download/beta-0.9/parity_linux_0.9.0-0_amd64.deb
PARITY_DEB_URL=https://github.com/ethcore/parity/releases/download/v1.0.0-rc1/parity_linux_1.0.0.rc1-0_amd64.deb
function run_installer()

21
json/Cargo.toml Normal file
View File

@@ -0,0 +1,21 @@
[package]
name = "ethjson"
version = "0.1.0"
authors = ["debris <marek.kotewicz@gmail.com>"]
build = "build.rs"
[dependencies]
ethcore-util = { path = "../util" }
rustc-serialize = "0.3"
serde = "0.7.0"
serde_json = "0.7.0"
serde_macros = { version = "0.7.0", optional = true }
clippy = { version = "0.0.54", optional = true }
[build-dependencies]
serde_codegen = { version = "0.7.0", optional = true }
syntex = "0.30.0"
[features]
default = ["serde_codegen"]
nightly = ["serde_macros"]

45
json/build.rs Normal file
View File

@@ -0,0 +1,45 @@
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
#[cfg(not(feature = "serde_macros"))]
mod inner {
extern crate syntex;
extern crate serde_codegen;
use std::env;
use std::path::Path;
pub fn main() {
let out_dir = env::var_os("OUT_DIR").unwrap();
let src = Path::new("src/lib.rs.in");
let dst = Path::new(&out_dir).join("lib.rs");
let mut registry = syntex::Registry::new();
serde_codegen::register(&mut registry);
registry.expand("", &src, &dst).unwrap();
}
}
#[cfg(feature = "serde_macros")]
mod inner {
pub fn main() {}
}
fn main() {
inner::main();
}

View File

@@ -0,0 +1,54 @@
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Blockchain test account deserializer.
use std::collections::BTreeMap;
use uint::Uint;
use bytes::Bytes;
/// Blockchain test account deserializer.
#[derive(Debug, PartialEq, Deserialize, Clone)]
pub struct Account {
/// Balance.
pub balance: Uint,
/// Code.
pub code: Bytes,
/// Nonce.
pub nonce: Uint,
/// Storage.
pub storage: BTreeMap<Uint, Uint>,
}
#[cfg(test)]
mod tests {
use serde_json;
use blockchain::account::Account;
#[test]
fn account_deserialization() {
let s = r#"{
"balance" : "0x09184e72a078",
"code" : "0x600140600155",
"nonce" : "0x00",
"storage" : {
"0x01" : "0x9a10c2b5bb8f3c602e674006d9b21f09167df57c87a78a5ce96d4159ecb76520"
}
}"#;
let _deserialized: Account= serde_json::from_str(s).unwrap();
// TODO: validate all fields
}
}

View File

@@ -0,0 +1,75 @@
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Blockchain test block deserializer.
use bytes::Bytes;
use blockchain::header::Header;
use blockchain::transaction::Transaction;
/// Blockchain test block deserializer.
#[derive(Debug, PartialEq, Deserialize)]
pub struct Block {
#[serde(rename="blockHeader")]
header: Option<Header>,
rlp: Bytes,
transactions: Option<Vec<Transaction>>,
#[serde(rename="uncleHeaders")]
uncles: Option<Vec<Header>>,
}
impl Block {
/// Returns block rlp.
pub fn rlp(&self) -> Vec<u8> {
self.rlp.clone().into()
}
}
#[cfg(test)]
mod tests {
use serde_json;
use blockchain::block::Block;
#[test]
fn block_deserialization() {
let s = r#"{
"blockHeader" : {
"bloom" : "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"coinbase" : "8888f1f195afa192cfee860698584c030f4c9db1",
"difficulty" : "0x020000",
"extraData" : "0x",
"gasLimit" : "0x2fefba",
"gasUsed" : "0x00",
"hash" : "65ebf1b97fb89b14680267e0723d69267ec4bf9a96d4a60ffcb356ae0e81c18f",
"mixHash" : "13735ab4156c9b36327224d92e1692fab8fc362f8e0f868c94d421848ef7cd06",
"nonce" : "931dcc53e5edc514",
"number" : "0x01",
"parentHash" : "5a39ed1020c04d4d84539975b893a4e7c53eab6c2965db8bc3468093a31bc5ae",
"receiptTrie" : "56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
"stateRoot" : "c5c83ff43741f573a0c9b31d0e56fdd745f4e37d193c4e78544f302777aafcf3",
"timestamp" : "0x56850b7b",
"transactionsTrie" : "56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
"uncleHash" : "1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347"
},
"blocknumber" : "1",
"rlp" : "0xf901fcf901f7a05a39ed1020c04d4d84539975b893a4e7c53eab6c2965db8bc3468093a31bc5aea01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347948888f1f195afa192cfee860698584c030f4c9db1a0c5c83ff43741f573a0c9b31d0e56fdd745f4e37d193c4e78544f302777aafcf3a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b90100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008302000001832fefba808456850b7b80a013735ab4156c9b36327224d92e1692fab8fc362f8e0f868c94d421848ef7cd0688931dcc53e5edc514c0c0",
"transactions" : [],
"uncleHeaders" : []
}"#;
let _deserialized: Block = serde_json::from_str(s).unwrap();
// TODO: validate all fields
}
}

View File

@@ -0,0 +1,182 @@
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Blockchain deserialization.
use bytes::Bytes;
use hash::H256;
use blockchain::state::State;
use blockchain::header::Header;
use blockchain::block::Block;
use spec::Genesis;
/// Blockchain deserialization.
#[derive(Debug, PartialEq, Deserialize)]
pub struct BlockChain {
/// Genesis block header.
#[serde(rename="genesisBlockHeader")]
pub genesis_block: Header,
/// Genesis block rlp.
#[serde(rename="genesisRLP")]
pub genesis_rlp: Option<Bytes>,
/// Blocks.
pub blocks: Vec<Block>,
/// Post state.
#[serde(rename="postState")]
pub post_state: State,
/// Pre state.
#[serde(rename="pre")]
pub pre_state: State,
/// Hash of best block.
#[serde(rename="lastblockhash")]
pub best_block: H256
}
impl BlockChain {
/// Returns blocks rlp.
pub fn blocks_rlp(&self) -> Vec<Vec<u8>> {
self.blocks.iter().map(|block| block.rlp()).collect()
}
/// Returns spec compatible genesis struct.
pub fn genesis(&self) -> Genesis {
Genesis {
nonce: Some(self.genesis_block.nonce.clone()),
mix_hash: Some(self.genesis_block.mix_hash.clone()),
seal_fields: None,
seal_rlp: None,
difficulty: self.genesis_block.difficulty,
author: self.genesis_block.author.clone(),
timestamp: self.genesis_block.timestamp,
parent_hash: self.genesis_block.parent_hash.clone(),
gas_limit: self.genesis_block.gas_limit,
transactions_root: Some(self.genesis_block.transactions_root.clone()),
receipts_root: Some(self.genesis_block.receipts_root.clone()),
state_root: Some(self.genesis_block.state_root.clone()),
gas_used: Some(self.genesis_block.gas_used),
extra_data: Some(self.genesis_block.extra_data.clone()),
}
}
}
#[cfg(test)]
mod tests {
use serde_json;
use blockchain::blockchain::BlockChain;
#[test]
fn blockchain_deserialization() {
let s = r#"{
"blocks" : [{
"blockHeader" : {
"bloom" : "00000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020000000000000000000800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020000000000040000000000000000000000000000000000000000000000000000000",
"coinbase" : "8888f1f195afa192cfee860698584c030f4c9db1",
"difficulty" : "0x020000",
"extraData" : "0x0102030405060708091011121314151617181920212223242526272829303132",
"gasLimit" : "0x2fefba",
"gasUsed" : "0x560b",
"hash" : "06b5b1742bde29468510c92641f36b719c61b3fc3e9a21c92a23978f4f7faa2a",
"mixHash" : "5266ca43e81d25925a9ba573c3e4f9180bc076d316d90e63c6f8708b272f5ce2",
"nonce" : "59ba4daed1898e21",
"number" : "0x01",
"parentHash" : "f052d217bd5275a5177a3c3b7debdfe2670f1c8394b2965ccd5c1883cc1a524d",
"receiptTrie" : "c7778a7376099ee2e5c455791c1885b5c361b95713fddcbe32d97fd01334d296",
"stateRoot" : "bac6177a79e910c98d86ec31a09ae37ac2de15b754fd7bed1ba52362c49416bf",
"timestamp" : "0x56850c2c",
"transactionsTrie" : "498785da562aa0c5dd5937cf15f22139b0b1bcf3b4fc48986e1bb1dae9292796",
"uncleHash" : "1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347"
},
"rlp" : "0xf90285f90219a0f052d217bd5275a5177a3c3b7debdfe2670f1c8394b2965ccd5c1883cc1a524da01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347948888f1f195afa192cfee860698584c030f4c9db1a0bac6177a79e910c98d86ec31a09ae37ac2de15b754fd7bed1ba52362c49416bfa0498785da562aa0c5dd5937cf15f22139b0b1bcf3b4fc48986e1bb1dae9292796a0c7778a7376099ee2e5c455791c1885b5c361b95713fddcbe32d97fd01334d296b90100000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000000000400000000000000000000000000000000000000000000000000000008302000001832fefba82560b8456850c2ca00102030405060708091011121314151617181920212223242526272829303132a05266ca43e81d25925a9ba573c3e4f9180bc076d316d90e63c6f8708b272f5ce28859ba4daed1898e21f866f864800a82c35094095e7baea6a6c7c4c2dfeb977efac326af552d8785012a05f200801ca0ee0b9ec878fbd4258a9473199d8ecc32996a20c323c004e79e0cda20e0418ce3a04e6bc63927d1510bab54f37e46fa036faf4b2c465d271920d9afea1fadf7bd21c0",
"transactions" : [
{
"data" : "0x",
"gasLimit" : "0xc350",
"gasPrice" : "0x0a",
"nonce" : "0x00",
"r" : "0xee0b9ec878fbd4258a9473199d8ecc32996a20c323c004e79e0cda20e0418ce3",
"s" : "0x4e6bc63927d1510bab54f37e46fa036faf4b2c465d271920d9afea1fadf7bd21",
"to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87",
"v" : "0x1c",
"value" : "0x012a05f200"
}
],
"uncleHeaders" : [
]
}],
"genesisBlockHeader" : {
"bloom" : "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"coinbase" : "8888f1f195afa192cfee860698584c030f4c9db1",
"difficulty" : "0x020000",
"extraData" : "0x42",
"gasLimit" : "0x2fefd8",
"gasUsed" : "0x00",
"hash" : "f052d217bd5275a5177a3c3b7debdfe2670f1c8394b2965ccd5c1883cc1a524d",
"mixHash" : "56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
"nonce" : "0102030405060708",
"number" : "0x00",
"parentHash" : "0000000000000000000000000000000000000000000000000000000000000000",
"receiptTrie" : "56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
"stateRoot" : "925002c3260b44e44c3edebad1cc442142b03020209df1ab8bb86752edbd2cd7",
"timestamp" : "0x54c98c81",
"transactionsTrie" : "56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
"uncleHash" : "1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347"
},
"genesisRLP" : "0xf901fcf901f7a00000000000000000000000000000000000000000000000000000000000000000a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347948888f1f195afa192cfee860698584c030f4c9db1a0925002c3260b44e44c3edebad1cc442142b03020209df1ab8bb86752edbd2cd7a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b90100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008302000080832fefd8808454c98c8142a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421880102030405060708c0c0",
"lastblockhash" : "06b5b1742bde29468510c92641f36b719c61b3fc3e9a21c92a23978f4f7faa2a",
"postState" : {
"095e7baea6a6c7c4c2dfeb977efac326af552d87" : {
"balance" : "0x012a05f264",
"code" : "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff600052600060206000a1",
"nonce" : "0x00",
"storage" : {
}
},
"8888f1f195afa192cfee860698584c030f4c9db1" : {
"balance" : "0x4563918244f75c6e",
"code" : "0x",
"nonce" : "0x00",
"storage" : {
}
},
"a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"balance" : "0x012a029592",
"code" : "0x",
"nonce" : "0x01",
"storage" : {
}
}
},
"pre" : {
"095e7baea6a6c7c4c2dfeb977efac326af552d87" : {
"balance" : "0x64",
"code" : "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff600052600060206000a1",
"nonce" : "0x00",
"storage" : {
}
},
"a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"balance" : "0x02540be400",
"code" : "0x",
"nonce" : "0x00",
"storage" : {
}
}
}
}"#;
let _deserialized: BlockChain = serde_json::from_str(s).unwrap();
// TODO: validate all fields
//}
}

View File

@@ -0,0 +1,98 @@
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Blockchain test header deserializer.
use hash::{H64, Address, H256, Bloom};
use uint::Uint;
use bytes::Bytes;
/// Blockchain test header deserializer.
#[derive(Debug, PartialEq, Deserialize)]
pub struct Header {
/// Blocks bloom.
pub bloom: Bloom,
/// Blocks author.
#[serde(rename="coinbase")]
pub author: Address,
/// Difficulty.
pub difficulty: Uint,
#[serde(rename="extraData")]
/// Extra data.
pub extra_data: Bytes,
/// Gas limit.
#[serde(rename="gasLimit")]
pub gas_limit: Uint,
/// Gas used.
#[serde(rename="gasUsed")]
pub gas_used: Uint,
/// Hash.
pub hash: H256,
#[serde(rename="mixHash")]
/// Mix hash.
pub mix_hash: H256,
/// Seal nonce.
pub nonce: H64,
/// Block number.
pub number: Uint,
/// Parent hash.
#[serde(rename="parentHash")]
pub parent_hash: H256,
/// Receipt root.
#[serde(rename="receiptTrie")]
pub receipts_root: H256,
/// State root.
#[serde(rename="stateRoot")]
pub state_root: H256,
/// Timestamp.
pub timestamp: Uint,
/// Transactions root.
#[serde(rename="transactionsTrie")]
pub transactions_root: H256,
/// Uncles hash.
#[serde(rename="uncleHash")]
pub uncles_hash: H256,
}
#[cfg(test)]
mod tests {
use serde_json;
use blockchain::header::Header;
#[test]
fn header_deserialization() {
let s = r#"{
"bloom" : "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"coinbase" : "8888f1f195afa192cfee860698584c030f4c9db1",
"difficulty" : "0x020000",
"extraData" : "0x",
"gasLimit" : "0x2fefba",
"gasUsed" : "0x00",
"hash" : "65ebf1b97fb89b14680267e0723d69267ec4bf9a96d4a60ffcb356ae0e81c18f",
"mixHash" : "13735ab4156c9b36327224d92e1692fab8fc362f8e0f868c94d421848ef7cd06",
"nonce" : "931dcc53e5edc514",
"number" : "0x01",
"parentHash" : "5a39ed1020c04d4d84539975b893a4e7c53eab6c2965db8bc3468093a31bc5ae",
"receiptTrie" : "56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
"stateRoot" : "c5c83ff43741f573a0c9b31d0e56fdd745f4e37d193c4e78544f302777aafcf3",
"timestamp" : "0x56850b7b",
"transactionsTrie" : "56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
"uncleHash" : "1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347"
}"#;
let _deserialized: Header = serde_json::from_str(s).unwrap();
// TODO: validate all fields
}
}

View File

@@ -0,0 +1,33 @@
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Blockchain test deserialization.
pub mod account;
pub mod block;
pub mod blockchain;
pub mod header;
pub mod state;
pub mod transaction;
pub mod test;
pub use self::account::Account;
pub use self::block::Block;
pub use self::blockchain::BlockChain;
pub use self::header::Header;
pub use self::state::State;
pub use self::test::Test;
pub use self::transaction::Transaction;

View File

@@ -0,0 +1,34 @@
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Blockchain test state deserializer.
use std::collections::BTreeMap;
use std::ops::Deref;
use hash::Address;
use blockchain::account::Account;
/// Blockchain test state deserializer.
#[derive(Debug, PartialEq, Deserialize, Clone)]
pub struct State(pub BTreeMap<Address, Account>);
impl Deref for State {
type Target = BTreeMap<Address, Account>;
fn deref(&self) -> &Self::Target {
&self.0
}
}

View File

@@ -0,0 +1,43 @@
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Blockchain test deserializer.
use std::collections::BTreeMap;
use std::ops::Deref;
use std::io::Read;
use serde_json;
use serde_json::Error;
use blockchain::blockchain::BlockChain;
/// Blockchain test deserializer.
#[derive(Debug, PartialEq, Deserialize)]
pub struct Test(BTreeMap<String, BlockChain>);
impl Deref for Test {
type Target = BTreeMap<String, BlockChain>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl Test {
/// Loads test from json.
pub fn load<R>(reader: R) -> Result<Self, Error> where R: Read {
serde_json::from_reader(reader)
}
}

View File

@@ -0,0 +1,35 @@
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Blockchain test transaction deserialization.
use uint::Uint;
use bytes::Bytes;
/// Blockchain test transaction deserialization.
#[derive(Debug, PartialEq, Deserialize)]
pub struct Transaction {
data: Bytes,
#[serde(rename="gasLimit")]
gas_limit: Uint,
#[serde(rename="gasPrice")]
gas_price: Uint,
nonce: Uint,
r: Uint,
s: Uint,
v: Uint,
value: Uint
}

83
json/src/bytes.rs Normal file
View File

@@ -0,0 +1,83 @@
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Lenient bytes json deserialization for test json files.
use rustc_serialize::hex::FromHex;
use serde::{Deserialize, Deserializer, Error};
use serde::de::Visitor;
/// Lenient bytes json deserialization for test json files.
#[derive(Default, Debug, PartialEq, Clone)]
pub struct Bytes(Vec<u8>);
impl Into<Vec<u8>> for Bytes {
fn into(self) -> Vec<u8> {
self.0
}
}
impl Deserialize for Bytes {
fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
where D: Deserializer {
deserializer.deserialize(BytesVisitor)
}
}
struct BytesVisitor;
impl Visitor for BytesVisitor {
type Value = Bytes;
fn visit_str<E>(&mut self, value: &str) -> Result<Self::Value, E> where E: Error {
let v = match value.len() {
0 => vec![],
2 if value.starts_with("0x") => vec![],
_ if value.starts_with("0x") => FromHex::from_hex(&value[2..]).unwrap_or(vec![]),
_ => FromHex::from_hex(value).unwrap_or(vec![]),
};
Ok(Bytes(v))
}
fn visit_string<E>(&mut self, value: String) -> Result<Self::Value, E> where E: Error {
self.visit_str(value.as_ref())
}
}
#[cfg(test)]
mod test {
use serde_json;
use bytes::Bytes;
#[test]
fn bytes_deserialization() {
let s = r#"["", "0x", "0x12", "1234"]"#;
let deserialized: Vec<Bytes> = serde_json::from_str(s).unwrap();
assert_eq!(deserialized, vec![
Bytes(vec![]),
Bytes(vec![]),
Bytes(vec![0x12]),
Bytes(vec![0x12, 0x34])
]);
}
#[test]
fn bytes_into() {
let bytes = Bytes(vec![0xff, 0x11]);
let v: Vec<u8> = bytes.into();
assert_eq!(vec![0xff, 0x11], v);
}
}

98
json/src/hash.rs Normal file
View File

@@ -0,0 +1,98 @@
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Lenient hash json deserialization for test json files.
use std::str::FromStr;
use serde::{Deserialize, Deserializer, Error};
use serde::de::Visitor;
use util::hash::{H64 as Hash64, Address as Hash160, H256 as Hash256, H2048 as Hash2048};
macro_rules! impl_hash {
($name: ident, $inner: ident) => {
/// Lenient hash json deserialization for test json files.
#[derive(Default, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Clone)]
pub struct $name($inner);
impl Into<$inner> for $name {
fn into(self) -> $inner {
self.0
}
}
impl Deserialize for $name {
fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
where D: Deserializer {
struct HashVisitor;
impl Visitor for HashVisitor {
type Value = $name;
fn visit_str<E>(&mut self, value: &str) -> Result<Self::Value, E> where E: Error {
let value = match value.len() {
0 => $inner::from(0),
2 if value == "0x" => $inner::from(0),
_ if value.starts_with("0x") => try!($inner::from_str(&value[2..]).map_err(|_| {
Error::custom(format!("Invalid hex value {}.", value).as_ref())
})),
_ => try!($inner::from_str(value).map_err(|_| {
Error::custom(format!("Invalid hex value {}.", value).as_ref())
}))
};
Ok($name(value))
}
fn visit_string<E>(&mut self, value: String) -> Result<Self::Value, E> where E: Error {
self.visit_str(value.as_ref())
}
}
deserializer.deserialize(HashVisitor)
}
}
}
}
impl_hash!(H64, Hash64);
impl_hash!(Address, Hash160);
impl_hash!(H256, Hash256);
impl_hash!(Bloom, Hash2048);
#[cfg(test)]
mod test {
use std::str::FromStr;
use serde_json;
use util::hash;
use hash::H256;
#[test]
fn hash_deserialization() {
let s = r#"["", "5a39ed1020c04d4d84539975b893a4e7c53eab6c2965db8bc3468093a31bc5ae"]"#;
let deserialized: Vec<H256> = serde_json::from_str(s).unwrap();
assert_eq!(deserialized, vec![
H256(hash::H256::from(0)),
H256(hash::H256::from_str("5a39ed1020c04d4d84539975b893a4e7c53eab6c2965db8bc3468093a31bc5ae").unwrap())
]);
}
#[test]
fn hash_into() {
assert_eq!(hash::H256::from(0), H256(hash::H256::from(0)).into());
}
}

28
json/src/lib.rs Normal file
View File

@@ -0,0 +1,28 @@
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Json deserialization module.
#![warn(missing_docs)]
#![cfg_attr(feature="nightly", feature(custom_derive, custom_attribute, plugin))]
#![cfg_attr(feature="nightly", plugin(serde_macros, clippy))]
#[cfg(feature = "serde_macros")]
include!("lib.rs.in");
#[cfg(not(feature = "serde_macros"))]
include!(concat!(env!("OUT_DIR"), "/lib.rs"));

26
json/src/lib.rs.in Normal file
View File

@@ -0,0 +1,26 @@
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
extern crate rustc_serialize;
extern crate serde;
extern crate serde_json;
extern crate ethcore_util as util;
pub mod hash;
pub mod uint;
pub mod bytes;
pub mod blockchain;
pub mod spec;

44
json/src/spec/account.rs Normal file
View File

@@ -0,0 +1,44 @@
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Spec account deserialization.
use uint::Uint;
use spec::builtin::Builtin;
/// Spec account.
#[derive(Debug, PartialEq, Deserialize)]
pub struct Account {
builtin: Option<Builtin>,
balance: Option<Uint>,
nonce: Option<Uint>,
}
#[cfg(test)]
mod tests {
use serde_json;
use spec::account::Account;
#[test]
fn account_deserialization() {
let s = r#"{
"balance": "1",
"builtin": { "name": "ecrecover", "pricing": { "linear": { "base": 3000, "word": 0 } } }
}"#;
let _deserialized: Account = serde_json::from_str(s).unwrap();
// TODO: validate all fields
}
}

55
json/src/spec/builtin.rs Normal file
View File

@@ -0,0 +1,55 @@
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Spec builtin deserialization.
/// Linear pricing.
#[derive(Debug, PartialEq, Deserialize)]
pub struct Linear {
base: u64,
word: u64,
}
/// Pricing variants.
#[derive(Debug, PartialEq, Deserialize)]
pub enum Pricing {
/// Linear pricing.
#[serde(rename="linear")]
Linear(Linear),
}
/// Spec builtin.
#[derive(Debug, PartialEq, Deserialize)]
pub struct Builtin {
name: String,
pricing: Pricing,
}
#[cfg(test)]
mod tests {
use serde_json;
use spec::builtin::Builtin;
#[test]
fn builtin_deserialization() {
let s = r#"{
"name": "ecrecover",
"pricing": { "linear": { "base": 3000, "word": 0 } }
}"#;
let _deserialized: Builtin = serde_json::from_str(s).unwrap();
// TODO: validate all fields
}
}

91
json/src/spec/genesis.rs Normal file
View File

@@ -0,0 +1,91 @@
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Spec genesis deserialization.
use uint::Uint;
use hash::{H64, Address, H256};
use bytes::Bytes;
/// Spec genesis.
#[derive(Debug, PartialEq, Deserialize)]
pub struct Genesis {
// old seal
/// Seal nonce.
pub nonce: Option<H64>,
#[serde(rename="mixHash")]
/// Seal mix hash.
pub mix_hash: Option<H256>,
// new seal // TODO: consider moving it to a separate seal structure
#[serde(rename="sealFields")]
/// Number of seal fields.
pub seal_fields: Option<usize>,
#[serde(rename="sealRlp")]
/// Seal rlp.
pub seal_rlp: Option<Bytes>,
/// Difficulty.
pub difficulty: Uint,
/// Block author.
pub author: Address,
/// Block timestamp.
pub timestamp: Uint,
/// Parent hash.
#[serde(rename="parentHash")]
pub parent_hash: H256,
/// Gas limit.
#[serde(rename="gasLimit")]
pub gas_limit: Uint,
/// Transactions root.
#[serde(rename="transactionsRoot")]
pub transactions_root: Option<H256>,
/// Receipts root.
#[serde(rename="receiptsRoot")]
pub receipts_root: Option<H256>,
/// State root.
#[serde(rename="stateRoot")]
pub state_root: Option<H256>,
/// Gas used.
#[serde(rename="gasUsed")]
pub gas_used: Option<Uint>,
/// Extra data.
#[serde(rename="extraData")]
pub extra_data: Option<Bytes>,
}
#[cfg(test)]
mod tests {
use serde_json;
use spec::genesis::Genesis;
#[test]
fn genesis_deserialization() {
let s = r#"{
"nonce": "0x0000000000000042",
"difficulty": "0x400000000",
"mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"author": "0x0000000000000000000000000000000000000000",
"timestamp": "0x00",
"parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"extraData": "0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa",
"gasLimit": "0x1388",
"stateRoot": "0xd7f8974fb5ac78d9ac099b9ad5018bedc2ce0a72dad1827a1709da30580f0544"
}"#;
let _deserialized: Genesis = serde_json::from_str(s).unwrap();
// TODO: validate all fields
}
}

29
json/src/spec/mod.rs Normal file
View File

@@ -0,0 +1,29 @@
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Spec deserialization.
pub mod account;
pub mod builtin;
pub mod genesis;
pub mod params;
pub mod spec;
pub use self::account::Account;
pub use self::builtin::Builtin;
pub use self::genesis::Genesis;
pub use self::params::Params;
pub use self::spec::Spec;

74
json/src/spec/params.rs Normal file
View File

@@ -0,0 +1,74 @@
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Spec params deserialization.
use uint::Uint;
use hash::Address;
/// Spec params.
#[derive(Debug, PartialEq, Deserialize)]
pub struct Params {
#[serde(rename="accountStartNonce")]
account_start_nonce: Uint,
#[serde(rename="frontierCompatibilityModeLimit")]
frontier_compatibility_mode_limit: Uint,
#[serde(rename="maximumExtraDataSize")]
maximum_extra_data_size: Uint,
#[serde(rename="tieBreakingGas")]
tie_breaking_gas: bool,
#[serde(rename="minGasLimit")]
min_gas_limit: Uint,
#[serde(rename="gasLimitBoundDivisor")]
gas_limit_bound_divisor: Uint,
#[serde(rename="minimumDifficulty")]
minimum_difficulty: Uint,
#[serde(rename="difficultyBoundDivisor")]
difficulty_bound_divisor: Uint,
#[serde(rename="durationLimit")]
duration_limit: Uint,
#[serde(rename="blockReward")]
block_reward: Uint,
registrar: Address,
#[serde(rename="networkID")]
network_id: Uint,
}
#[cfg(test)]
mod tests {
use serde_json;
use spec::params::Params;
#[test]
fn params_deserialization() {
let s = r#"{
"accountStartNonce": "0x00",
"frontierCompatibilityModeLimit": "0x118c30",
"maximumExtraDataSize": "0x20",
"tieBreakingGas": false,
"minGasLimit": "0x1388",
"gasLimitBoundDivisor": "0x0400",
"minimumDifficulty": "0x020000",
"difficultyBoundDivisor": "0x0800",
"durationLimit": "0x0d",
"blockReward": "0x4563918244F40000",
"registrar" : "0xc6d9d2cd449a754c494264e1809c50e34d64562b",
"networkID" : "0x1"
}"#;
let _deserialized: Params = serde_json::from_str(s).unwrap();
// TODO: validate all fields
}
}

84
json/src/spec/spec.rs Normal file
View File

@@ -0,0 +1,84 @@
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Spec deserialization.
use std::collections::BTreeMap;
use hash::Address;
use spec::account::Account;
use spec::params::Params;
use spec::genesis::Genesis;
/// Spec deserialization.
#[derive(Debug, PartialEq, Deserialize)]
pub struct Spec {
name: String,
#[serde(rename="engineName")]
engine_name: String, // TODO: consider making it an enum
params: Params,
genesis: Genesis,
accounts: BTreeMap<Address, Account>,
}
#[cfg(test)]
mod tests {
use serde_json;
use spec::spec::Spec;
#[test]
fn spec_deserialization() {
let s = r#"{
"name": "Morden",
"engineName": "Ethash",
"params": {
"accountStartNonce": "0x0100000",
"frontierCompatibilityModeLimit": "0x789b0",
"maximumExtraDataSize": "0x20",
"tieBreakingGas": false,
"minGasLimit": "0x1388",
"gasLimitBoundDivisor": "0x0400",
"minimumDifficulty": "0x020000",
"difficultyBoundDivisor": "0x0800",
"durationLimit": "0x0d",
"blockReward": "0x4563918244F40000",
"registrar": "",
"networkID" : "0x2"
},
"genesis": {
"nonce": "0x00006d6f7264656e",
"difficulty": "0x20000",
"mixHash": "0x00000000000000000000000000000000000000647572616c65787365646c6578",
"author": "0x0000000000000000000000000000000000000000",
"timestamp": "0x00",
"parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"extraData": "0x",
"gasLimit": "0x2fefd8"
},
"nodes": [
"enode://b1217cbaa440e35ed471157123fe468e19e8b5ad5bedb4b1fdbcbdab6fb2f5ed3e95dd9c24a22a79fdb2352204cea207df27d92bfd21bfd41545e8b16f637499@104.44.138.37:30303"
],
"accounts": {
"0000000000000000000000000000000000000001": { "balance": "1", "nonce": "1048576", "builtin": { "name": "ecrecover", "pricing": { "linear": { "base": 3000, "word": 0 } } } },
"0000000000000000000000000000000000000002": { "balance": "1", "nonce": "1048576", "builtin": { "name": "sha256", "pricing": { "linear": { "base": 60, "word": 12 } } } },
"0000000000000000000000000000000000000003": { "balance": "1", "nonce": "1048576", "builtin": { "name": "ripemd160", "pricing": { "linear": { "base": 600, "word": 120 } } } },
"0000000000000000000000000000000000000004": { "balance": "1", "nonce": "1048576", "builtin": { "name": "identity", "pricing": { "linear": { "base": 15, "word": 3 } } } },
"102e61f5d8f9bc71d0ad4a084df4e65e05ce0e1c": { "balance": "1606938044258990275541962092341162602522202993782792835301376", "nonce": "1048576" }
}
}"#;
let _deserialized: Spec = serde_json::from_str(s).unwrap();
// TODO: validate all fields
}
}

94
json/src/uint.rs Normal file
View File

@@ -0,0 +1,94 @@
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Lenient uint json deserialization for test json files.
use std::str::FromStr;
use serde::{Deserialize, Deserializer, Error};
use serde::de::Visitor;
use util::numbers::{U256, Uint as U};
/// Lenient uint json deserialization for test json files.
#[derive(Default, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
pub struct Uint(U256);
impl Into<U256> for Uint {
fn into(self) -> U256 {
self.0
}
}
impl Into<u64> for Uint {
fn into(self) -> u64 {
u64::from(self.0)
}
}
impl Deserialize for Uint {
fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
where D: Deserializer {
deserializer.deserialize(UintVisitor)
}
}
struct UintVisitor;
impl Visitor for UintVisitor {
type Value = Uint;
fn visit_str<E>(&mut self, value: &str) -> Result<Self::Value, E> where E: Error {
let value = match value.len() {
0 => U256::from(0),
2 if value.starts_with("0x") => U256::from(0),
_ if value.starts_with("0x") => try!(U256::from_str(&value[2..]).map_err(|_| {
Error::custom(format!("Invalid hex value {}.", value).as_ref())
})),
_ => try!(U256::from_dec_str(value).map_err(|_| {
Error::custom(format!("Invalid decimal value {}.", value).as_ref())
}))
};
Ok(Uint(value))
}
fn visit_string<E>(&mut self, value: String) -> Result<Self::Value, E> where E: Error {
self.visit_str(value.as_ref())
}
}
#[cfg(test)]
mod test {
use serde_json;
use util::numbers::U256;
use uint::Uint;
#[test]
fn uint_deserialization() {
let s = r#"["0xa", "10", "", "0x"]"#;
let deserialized: Vec<Uint> = serde_json::from_str(s).unwrap();
assert_eq!(deserialized, vec![
Uint(U256::from(10)),
Uint(U256::from(10)),
Uint(U256::from(0)),
Uint(U256::from(0))
]);
}
#[test]
fn uint_into() {
assert_eq!(U256::from(10), Uint(U256::from(10)).into());
}
}

View File

@@ -3,7 +3,7 @@ description = "Ethminer library"
homepage = "http://ethcore.io"
license = "GPL-3.0"
name = "ethminer"
version = "1.1.0"
version = "1.0.0"
authors = ["Ethcore <admin@ethcore.io>"]
build = "build.rs"
@@ -17,7 +17,7 @@ log = "0.3"
env_logger = "0.3"
rustc-serialize = "0.3"
rayon = "0.3.1"
clippy = { version = "0.0.50", optional = true }
clippy = { version = "0.0.54", optional = true }
[features]
default = []

View File

@@ -42,10 +42,9 @@
//!
//! let miner: Miner = Miner::default();
//! // get status
//! assert_eq!(miner.status().transaction_queue_pending, 0);
//! assert_eq!(miner.status().transactions_in_pending_queue, 0);
//!
//! // Check block for sealing
//! miner.prepare_sealing(client.deref());
//! assert!(miner.sealing_block(client.deref()).lock().unwrap().is_some());
//! }
//! ```
@@ -62,11 +61,11 @@ extern crate rayon;
mod miner;
mod transaction_queue;
pub use transaction_queue::TransactionQueue;
pub use transaction_queue::{TransactionQueue, AccountDetails};
pub use miner::{Miner};
use std::sync::Mutex;
use util::{H256, U256, Address, Bytes};
use util::{H256, U256, Address, FixedHash, Bytes};
use ethcore::client::{BlockChainClient};
use ethcore::block::{ClosedBlock};
use ethcore::error::{Error};
@@ -78,9 +77,15 @@ pub trait MinerService : Send + Sync {
/// Returns miner's status.
fn status(&self) -> MinerStatus;
/// Get the author that we will seal blocks as.
fn author(&self) -> Address { Address::zero() }
/// Get the extra_data that we will seal blocks wuth.
fn extra_data(&self) -> Bytes { vec![] }
/// Imports transactions to transaction queue.
fn import_transactions<T>(&self, transactions: Vec<SignedTransaction>, fetch_nonce: T) -> Result<(), Error>
where T: Fn(&Address) -> U256;
fn import_transactions<T>(&self, transactions: Vec<SignedTransaction>, fetch_account: T) -> Vec<Result<(), Error>>
where T: Fn(&Address) -> AccountDetails;
/// Returns hashes of transactions currently in pending
fn pending_transactions_hashes(&self) -> Vec<H256>;
@@ -92,7 +97,7 @@ pub trait MinerService : Send + Sync {
fn chain_new_blocks(&self, chain: &BlockChainClient, imported: &[H256], invalid: &[H256], enacted: &[H256], retracted: &[H256]);
/// New chain head event. Restart mining operation.
fn prepare_sealing(&self, chain: &BlockChainClient);
fn update_sealing(&self, chain: &BlockChainClient);
/// Grab the `ClosedBlock` that we want to be sealed. Comes as a mutex that you have to lock.
fn sealing_block(&self, chain: &BlockChainClient) -> &Mutex<Option<ClosedBlock>>;
@@ -100,12 +105,26 @@ pub trait MinerService : Send + Sync {
/// Submit `seal` as a valid solution for the header of `pow_hash`.
/// Will check the seal, but not actually insert the block into the chain.
fn submit_seal(&self, chain: &BlockChainClient, pow_hash: H256, seal: Vec<Bytes>) -> Result<(), Error>;
/// Query pending transactions for hash
fn transaction(&self, hash: &H256) -> Option<SignedTransaction>;
/// Get a list of all pending transactions.
fn pending_transactions(&self) -> Vec<SignedTransaction>;
/// Returns highest transaction nonce for given address.
fn last_nonce(&self, address: &Address) -> Option<U256>;
/// Suggested gas price
fn sensible_gas_price(&self) -> U256 { x!(20000000000u64) }
}
/// Mining status
pub struct MinerStatus {
/// Number of transactions in queue with state `pending` (ready to be included in block)
pub transaction_queue_pending: usize,
pub transactions_in_pending_queue: usize,
/// Number of transactions in queue with state `future` (not yet ready to be included in block)
pub transaction_queue_future: usize,
pub transactions_in_future_queue: usize,
/// Number of transactions included in currently mined block
pub transactions_in_pending_block: usize,
}

View File

@@ -18,14 +18,15 @@ use rayon::prelude::*;
use std::sync::{Mutex, RwLock, Arc};
use std::sync::atomic;
use std::sync::atomic::AtomicBool;
use std::collections::HashSet;
use util::{H256, U256, Address, Bytes, Uint};
use ethcore::views::{BlockView};
use ethcore::views::{BlockView, HeaderView};
use ethcore::client::{BlockChainClient, BlockId};
use ethcore::block::{ClosedBlock};
use ethcore::block::{ClosedBlock, IsBlock};
use ethcore::error::{Error};
use ethcore::transaction::SignedTransaction;
use super::{MinerService, MinerStatus, TransactionQueue};
use super::{MinerService, MinerStatus, TransactionQueue, AccountDetails};
/// Keeps track of transactions using priority queue and holds currently mined block.
pub struct Miner {
@@ -33,6 +34,7 @@ pub struct Miner {
// for sealing...
sealing_enabled: AtomicBool,
sealing_block_last_request: Mutex<u64>,
sealing_block: Mutex<Option<ClosedBlock>>,
gas_floor_target: RwLock<U256>,
author: RwLock<Address>,
@@ -45,6 +47,7 @@ impl Default for Miner {
Miner {
transaction_queue: Mutex::new(TransactionQueue::new()),
sealing_enabled: AtomicBool::new(false),
sealing_block_last_request: Mutex::new(0),
sealing_block: Mutex::new(None),
gas_floor_target: RwLock::new(U256::zero()),
author: RwLock::new(Address::default()),
@@ -71,7 +74,7 @@ impl Miner {
/// Get the extra_data that we will seal blocks wuth.
fn gas_floor_target(&self) -> U256 {
self.gas_floor_target.read().unwrap().clone()
*self.gas_floor_target.read().unwrap()
}
/// Set the author that we will seal blocks as.
@@ -93,27 +96,73 @@ impl Miner {
pub fn set_minimal_gas_price(&self, min_gas_price: U256) {
self.transaction_queue.lock().unwrap().set_minimal_gas_price(min_gas_price);
}
/// Prepares new block for sealing including top transactions from queue.
fn prepare_sealing(&self, chain: &BlockChainClient) {
let transactions = self.transaction_queue.lock().unwrap().top_transactions();
let b = chain.prepare_sealing(
self.author(),
self.gas_floor_target(),
self.extra_data(),
transactions,
);
*self.sealing_block.lock().unwrap() = b.map(|(block, invalid_transactions)| {
let mut queue = self.transaction_queue.lock().unwrap();
queue.remove_all(
&invalid_transactions.into_iter().collect::<Vec<H256>>(),
|a: &Address| AccountDetails {
nonce: chain.nonce(a),
balance: chain.balance(a),
}
);
block
});
}
fn update_gas_limit(&self, chain: &BlockChainClient) {
let gas_limit = HeaderView::new(&chain.best_block_header()).gas_limit();
let mut queue = self.transaction_queue.lock().unwrap();
queue.set_gas_limit(gas_limit);
}
}
const SEALING_TIMEOUT_IN_BLOCKS : u64 = 5;
impl MinerService for Miner {
fn clear_and_reset(&self, chain: &BlockChainClient) {
self.transaction_queue.lock().unwrap().clear();
self.prepare_sealing(chain);
self.update_sealing(chain);
}
fn status(&self) -> MinerStatus {
let status = self.transaction_queue.lock().unwrap().status();
let block = self.sealing_block.lock().unwrap();
MinerStatus {
transaction_queue_pending: status.pending,
transaction_queue_future: status.future,
transactions_in_pending_queue: status.pending,
transactions_in_future_queue: status.future,
transactions_in_pending_block: block.as_ref().map_or(0, |b| b.transactions().len()),
}
}
fn import_transactions<T>(&self, transactions: Vec<SignedTransaction>, fetch_nonce: T) -> Result<(), Error>
where T: Fn(&Address) -> U256 {
fn sensible_gas_price(&self) -> U256 {
// 10% above our minimum.
self.transaction_queue.lock().unwrap().minimal_gas_price().clone() * x!(110) / x!(100)
}
fn author(&self) -> Address {
*self.author.read().unwrap()
}
fn extra_data(&self) -> Bytes {
self.extra_data.read().unwrap().clone()
}
fn import_transactions<T>(&self, transactions: Vec<SignedTransaction>, fetch_account: T) -> Vec<Result<(), Error>>
where T: Fn(&Address) -> AccountDetails {
let mut transaction_queue = self.transaction_queue.lock().unwrap();
transaction_queue.add_all(transactions, fetch_nonce)
transaction_queue.add_all(transactions, fetch_account)
}
fn pending_transactions_hashes(&self) -> Vec<H256> {
@@ -121,26 +170,47 @@ impl MinerService for Miner {
transaction_queue.pending_hashes()
}
fn prepare_sealing(&self, chain: &BlockChainClient) {
let no_of_transactions = 128;
// TODO: should select transactions orm queue according to gas limit of block.
let transactions = self.transaction_queue.lock().unwrap().top_transactions(no_of_transactions);
fn transaction(&self, hash: &H256) -> Option<SignedTransaction> {
let queue = self.transaction_queue.lock().unwrap();
queue.find(hash)
}
let b = chain.prepare_sealing(
self.author(),
self.gas_floor_target(),
self.extra_data(),
transactions,
);
*self.sealing_block.lock().unwrap() = b;
fn pending_transactions(&self) -> Vec<SignedTransaction> {
let queue = self.transaction_queue.lock().unwrap();
queue.top_transactions()
}
fn last_nonce(&self, address: &Address) -> Option<U256> {
self.transaction_queue.lock().unwrap().last_nonce(address)
}
fn update_sealing(&self, chain: &BlockChainClient) {
if self.sealing_enabled.load(atomic::Ordering::Relaxed) {
let current_no = chain.chain_info().best_block_number;
let last_request = *self.sealing_block_last_request.lock().unwrap();
let should_disable_sealing = current_no > last_request && current_no - last_request > SEALING_TIMEOUT_IN_BLOCKS;
if should_disable_sealing {
trace!(target: "miner", "Miner sleeping (current {}, last {})", current_no, last_request);
self.sealing_enabled.store(false, atomic::Ordering::Relaxed);
*self.sealing_block.lock().unwrap() = None;
} else {
self.prepare_sealing(chain);
}
}
}
fn sealing_block(&self, chain: &BlockChainClient) -> &Mutex<Option<ClosedBlock>> {
if self.sealing_block.lock().unwrap().is_none() {
self.sealing_enabled.store(true, atomic::Ordering::Relaxed);
// TODO: Above should be on a timer that resets after two blocks have arrived without being asked for.
self.prepare_sealing(chain);
}
let mut sealing_block_last_request = self.sealing_block_last_request.lock().unwrap();
let best_number = chain.chain_info().best_block_number;
if *sealing_block_last_request != best_number {
trace!(target: "miner", "Miner received request (was {}, now {}) - waking up.", *sealing_block_last_request, best_number);
*sealing_block_last_request = best_number;
}
&self.sealing_block
}
@@ -175,32 +245,92 @@ impl MinerService for Miner {
block.transactions()
}
// First update gas limit in transaction queue
self.update_gas_limit(chain);
// Then import all transactions...
{
let in_chain = vec![imported, enacted, invalid];
let in_chain = in_chain
.par_iter()
.flat_map(|h| h.par_iter().map(|h| fetch_transactions(chain, h)));
let out_of_chain = retracted
.par_iter()
.map(|h| fetch_transactions(chain, h));
in_chain.for_each(|txs| {
let mut transaction_queue = self.transaction_queue.lock().unwrap();
let hashes = txs.iter().map(|tx| tx.hash()).collect::<Vec<H256>>();
transaction_queue.remove_all(&hashes, |a| chain.nonce(a));
});
out_of_chain.for_each(|txs| {
// populate sender
for tx in &txs {
let _sender = tx.sender();
}
let mut transaction_queue = self.transaction_queue.lock().unwrap();
let _ = transaction_queue.add_all(txs, |a| chain.nonce(a));
let _ = transaction_queue.add_all(txs, |a| AccountDetails {
nonce: chain.nonce(a),
balance: chain.balance(a)
});
});
}
if self.sealing_enabled.load(atomic::Ordering::Relaxed) {
self.prepare_sealing(chain);
// ...and after that remove old ones
{
let in_chain = {
let mut in_chain = HashSet::new();
in_chain.extend(imported);
in_chain.extend(enacted);
in_chain.extend(invalid);
in_chain
.into_iter()
.collect::<Vec<H256>>()
};
let in_chain = in_chain
.par_iter()
.map(|h: &H256| fetch_transactions(chain, h));
in_chain.for_each(|txs| {
let hashes = txs.iter().map(|tx| tx.hash()).collect::<Vec<H256>>();
let mut transaction_queue = self.transaction_queue.lock().unwrap();
transaction_queue.remove_all(&hashes, |a| AccountDetails {
nonce: chain.nonce(a),
balance: chain.balance(a)
});
});
}
self.update_sealing(chain);
}
}
#[cfg(test)]
mod tests {
use MinerService;
use super::{Miner};
use ethcore::client::{TestBlockChainClient, EachBlockWith};
// TODO [ToDr] To uncomment client is cleaned from mining stuff.
#[ignore]
#[test]
fn should_prepare_block_to_seal() {
// given
let client = TestBlockChainClient::default();
let miner = Miner::default();
// when
let res = miner.sealing_block(&client);
// then
assert!(res.lock().unwrap().is_some(), "Expected closed block");
}
#[test]
fn should_reset_seal_after_couple_of_blocks() {
// given
let client = TestBlockChainClient::default();
let miner = Miner::default();
let res = miner.sealing_block(&client);
// TODO [ToDr] Uncomment after fixing TestBlockChainClient
// assert!(res.lock().unwrap().is_some(), "Expected closed block");
// when
client.add_blocks(10, EachBlockWith::Uncle);
// then
assert!(res.lock().unwrap().is_none(), "Expected to remove sealed block");
}
}

View File

@@ -34,7 +34,7 @@
//! use util::crypto::KeyPair;
//! use util::hash::Address;
//! use util::numbers::{Uint, U256};
//! use ethminer::TransactionQueue;
//! use ethminer::{TransactionQueue, AccountDetails};
//! use ethcore::transaction::*;
//! use rustc_serialize::hex::FromHex;
//!
@@ -47,16 +47,19 @@
//!
//! let st1 = t1.sign(&key.secret());
//! let st2 = t2.sign(&key.secret());
//! let default_nonce = |_a: &Address| U256::from(10);
//! let default_nonce = |_a: &Address| AccountDetails {
//! nonce: U256::from(10),
//! balance: U256::from(1_000_000),
//! };
//!
//! let mut txq = TransactionQueue::new();
//! txq.add(st2.clone(), &default_nonce);
//! txq.add(st1.clone(), &default_nonce);
//! txq.add(st2.clone(), &default_nonce).unwrap();
//! txq.add(st1.clone(), &default_nonce).unwrap();
//!
//! // Check status
//! assert_eq!(txq.status().pending, 2);
//! // Check top transactions
//! let top = txq.top_transactions(3);
//! let top = txq.top_transactions();
//! assert_eq!(top.len(), 2);
//! assert_eq!(top[0], st1);
//! assert_eq!(top[1], st2);
@@ -66,7 +69,7 @@
//! txq.remove(&st1.hash(), &default_nonce);
//! assert_eq!(txq.status().pending, 0);
//! assert_eq!(txq.status().future, 1);
//! assert_eq!(txq.top_transactions(3).len(), 0);
//! assert_eq!(txq.top_transactions().len(), 0);
//! }
//! ```
//!
@@ -189,7 +192,12 @@ impl TransactionSet {
/// Inserts `TransactionOrder` to this set
fn insert(&mut self, sender: Address, nonce: U256, order: TransactionOrder) -> Option<TransactionOrder> {
self.by_priority.insert(order.clone());
self.by_address.insert(sender, nonce, order)
let r = self.by_address.insert(sender, nonce, order);
// If transaction was replaced remove it from priority queue
if let Some(ref order) = r {
self.by_priority.remove(order);
}
r
}
/// Remove low priority transactions if there is more then specified by given `limit`.
@@ -205,14 +213,15 @@ impl TransactionSet {
self.by_priority
.iter()
.skip(self.limit)
.map(|order| by_hash.get(&order.hash).expect("Inconsistency in queue detected."))
.map(|order| by_hash.get(&order.hash)
.expect("All transactions in `self.by_priority` and `self.by_address` are kept in sync with `by_hash`."))
.map(|tx| (tx.sender(), tx.nonce()))
.collect()
};
for (sender, nonce) in to_drop {
let order = self.drop(&sender, &nonce).expect("Dropping transaction found in priority queue failed.");
by_hash.remove(&order.hash).expect("Inconsistency in queue.");
let order = self.drop(&sender, &nonce).expect("Transaction has just been found in `by_priority`; so it is in `by_address` also.");
by_hash.remove(&order.hash).expect("Hash found in `by_priorty` matches the one dropped; so it is included in `by_hash`");
}
}
@@ -232,8 +241,6 @@ impl TransactionSet {
}
}
// Will be used when rpc merged
#[allow(dead_code)]
#[derive(Debug)]
/// Current status of the queue
pub struct TransactionQueueStatus {
@@ -243,10 +250,23 @@ pub struct TransactionQueueStatus {
pub future: usize,
}
/// Details of account
pub struct AccountDetails {
/// Most recent account nonce
pub nonce: U256,
/// Current account balance
pub balance: U256,
}
/// Transactions with `gas > (gas_limit + gas_limit * Factor(in percents))` are not imported to the queue.
const GAS_LIMIT_HYSTERESIS: usize = 10; // %
/// TransactionQueue implementation
pub struct TransactionQueue {
/// Gas Price threshold for transactions that can be imported to this queue (defaults to 0)
minimal_gas_price: U256,
/// Current gas limit (block gas limit * factor). Transactions above the limit will not be accepted (default to !0)
gas_limit: U256,
/// Priority queue for transactions that can go to block
current: TransactionSet,
/// Priority queue for transactions that has been received but are not yet valid to go to block
@@ -284,6 +304,7 @@ impl TransactionQueue {
TransactionQueue {
minimal_gas_price: U256::zero(),
gas_limit: !U256::zero(),
current: current,
future: future,
by_hash: HashMap::new(),
@@ -291,12 +312,28 @@ impl TransactionQueue {
}
}
/// Get the minimal gas price.
pub fn minimal_gas_price(&self) -> &U256 {
&self.minimal_gas_price
}
/// Sets new gas price threshold for incoming transactions.
/// Any transactions already imported to the queue are not affected.
/// Any transaction already imported to the queue is not affected.
pub fn set_minimal_gas_price(&mut self, min_gas_price: U256) {
self.minimal_gas_price = min_gas_price;
}
/// Sets new gas limit. Transactions with gas slightly (`GAS_LIMIT_HYSTERESIS`) above the limit won't be imported.
/// Any transaction already imported to the queue is not affected.
pub fn set_gas_limit(&mut self, gas_limit: U256) {
let extra = gas_limit / U256::from(GAS_LIMIT_HYSTERESIS);
self.gas_limit = match gas_limit.overflowing_add(extra) {
(_, true) => !U256::zero(),
(val, false) => val,
};
}
// Will be used when rpc merged
#[allow(dead_code)]
/// Returns current status for this queue
@@ -308,49 +345,76 @@ impl TransactionQueue {
}
/// Adds all signed transactions to queue to be verified and imported
pub fn add_all<T>(&mut self, txs: Vec<SignedTransaction>, fetch_nonce: T) -> Result<(), Error>
where T: Fn(&Address) -> U256 {
for tx in txs.into_iter() {
try!(self.add(tx, &fetch_nonce));
}
Ok(())
pub fn add_all<T>(&mut self, txs: Vec<SignedTransaction>, fetch_account: T) -> Vec<Result<(), Error>>
where T: Fn(&Address) -> AccountDetails {
txs.into_iter()
.map(|tx| self.add(tx, &fetch_account))
.collect()
}
/// Add signed transaction to queue to be verified and imported
pub fn add<T>(&mut self, tx: SignedTransaction, fetch_nonce: &T) -> Result<(), Error>
where T: Fn(&Address) -> U256 {
pub fn add<T>(&mut self, tx: SignedTransaction, fetch_account: &T) -> Result<(), Error>
where T: Fn(&Address) -> AccountDetails {
trace!(target: "miner", "Importing: {:?}", tx.hash());
if tx.gas_price < self.minimal_gas_price {
trace!(target: "sync",
trace!(target: "miner",
"Dropping transaction below minimal gas price threshold: {:?} (gp: {} < {})",
tx.hash(), tx.gas_price, self.minimal_gas_price
);
return Err(Error::Transaction(TransactionError::InsufficientGasPrice{
return Err(Error::Transaction(TransactionError::InsufficientGasPrice {
minimal: self.minimal_gas_price,
got: tx.gas_price
got: tx.gas_price,
}));
}
self.import_tx(try!(VerifiedTransaction::new(tx)), fetch_nonce);
Ok(())
if tx.gas > self.gas_limit {
trace!(target: "miner",
"Dropping transaction above gas limit: {:?} ({} > {})",
tx.hash(), tx.gas, self.gas_limit
);
return Err(Error::Transaction(TransactionError::GasLimitExceeded {
limit: self.gas_limit,
got: tx.gas,
}));
}
let vtx = try!(VerifiedTransaction::new(tx));
let account = fetch_account(&vtx.sender());
let cost = vtx.transaction.value + vtx.transaction.gas_price * vtx.transaction.gas;
if account.balance < cost {
trace!(target: "miner", "Dropping transaction without sufficient balance: {:?} ({} < {})",
vtx.hash(), account.balance, cost);
return Err(Error::Transaction(TransactionError::InsufficientBalance {
cost: cost,
balance: account.balance
}));
}
self.import_tx(vtx, account.nonce).map_err(Error::Transaction)
}
/// Removes all transactions identified by hashes given in slice
///
/// If gap is introduced marks subsequent transactions as future
pub fn remove_all<T>(&mut self, transaction_hashes: &[H256], fetch_nonce: T)
where T: Fn(&Address) -> U256 {
pub fn remove_all<T>(&mut self, transaction_hashes: &[H256], fetch_account: T)
where T: Fn(&Address) -> AccountDetails {
for hash in transaction_hashes {
self.remove(&hash, &fetch_nonce);
self.remove(&hash, &fetch_account);
}
}
/// Removes transaction identified by hashes from queue.
///
/// If gap is introduced marks subsequent transactions as future
pub fn remove<T>(&mut self, transaction_hash: &H256, fetch_nonce: &T)
where T: Fn(&Address) -> U256 {
pub fn remove<T>(&mut self, transaction_hash: &H256, fetch_account: &T)
where T: Fn(&Address) -> AccountDetails {
let transaction = self.by_hash.remove(transaction_hash);
if transaction.is_none() {
// We don't know this transaction
@@ -360,7 +424,8 @@ impl TransactionQueue {
let transaction = transaction.unwrap();
let sender = transaction.sender();
let nonce = transaction.nonce();
let current_nonce = fetch_nonce(&sender);
let current_nonce = fetch_account(&sender).nonce;
// Remove from future
let order = self.future.drop(&sender, &nonce);
@@ -401,6 +466,7 @@ impl TransactionQueue {
if k >= current_nonce {
self.future.insert(*sender, k, order.update_height(k, current_nonce));
} else {
trace!(target: "miner", "Dropping old transaction: {:?} (nonce: {} < {})", order.hash, k, current_nonce);
// Remove the transaction completely
self.by_hash.remove(&order.hash);
}
@@ -421,20 +487,18 @@ impl TransactionQueue {
if k >= current_nonce {
self.future.insert(*sender, k, order.update_height(k, current_nonce));
} else {
trace!(target: "miner", "Dropping old transaction: {:?} (nonce: {} < {})", order.hash, k, current_nonce);
self.by_hash.remove(&order.hash);
}
}
self.future.enforce_limit(&mut self.by_hash);
}
// Will be used when mining merged
#[allow(dead_code)]
/// Returns top transactions from the queue ordered by priority.
pub fn top_transactions(&self, size: usize) -> Vec<SignedTransaction> {
pub fn top_transactions(&self) -> Vec<SignedTransaction> {
self.current.by_priority
.iter()
.take(size)
.map(|t| self.by_hash.get(&t.hash).expect("Transaction Queue Inconsistency"))
.map(|t| self.by_hash.get(&t.hash).expect("All transactions in `current` and `future` are always included in `by_hash`"))
.map(|t| t.transaction.clone())
.collect()
}
@@ -447,6 +511,11 @@ impl TransactionQueue {
.collect()
}
/// Finds transaction in the queue by hash (if any)
pub fn find(&self, hash: &H256) -> Option<SignedTransaction> {
match self.by_hash.get(hash) { Some(transaction_ref) => Some(transaction_ref.transaction.clone()), None => None }
}
/// Removes all elements (in any state) from the queue
pub fn clear(&mut self) {
self.current.clear();
@@ -455,6 +524,11 @@ impl TransactionQueue {
self.last_nonces.clear();
}
/// Returns highest transaction nonce for given address.
pub fn last_nonce(&self, address: &Address) -> Option<U256> {
self.last_nonces.get(address).cloned()
}
/// Checks if there are any transactions in `future` that should actually be promoted to `current`
/// (because nonce matches).
fn move_matching_future_to_current(&mut self, address: Address, mut current_nonce: U256, first_nonce: U256) {
@@ -486,19 +560,20 @@ impl TransactionQueue {
///
/// It ignores transactions that has already been imported (same `hash`) and replaces the transaction
/// iff `(address, nonce)` is the same but `gas_price` is higher.
fn import_tx<T>(&mut self, tx: VerifiedTransaction, fetch_nonce: &T)
where T: Fn(&Address) -> U256 {
///
/// Returns `true` when transaction was imported successfuly
fn import_tx(&mut self, tx: VerifiedTransaction, state_nonce: U256) -> Result<(), TransactionError> {
if self.by_hash.get(&tx.hash()).is_some() {
// Transaction is already imported.
trace!(target: "sync", "Dropping already imported transaction with hash: {:?}", tx.hash());
return;
trace!(target: "miner", "Dropping already imported transaction: {:?}", tx.hash());
return Err(TransactionError::AlreadyImported);
}
let address = tx.sender();
let nonce = tx.nonce();
let state_nonce = fetch_nonce(&address);
let next_nonce = self.last_nonces
.get(&address)
.cloned()
@@ -509,18 +584,32 @@ impl TransactionQueue {
// We have a gap - put to future
Self::replace_transaction(tx, next_nonce, &mut self.future, &mut self.by_hash);
self.future.enforce_limit(&mut self.by_hash);
return;
return Ok(());
} else if nonce < state_nonce {
// Droping transaction
trace!(target: "sync", "Dropping transaction with nonce: {} - expecting: {}", nonce, next_nonce);
return;
trace!(target: "miner", "Dropping old transaction: {:?} (nonce: {} < {})", tx.hash(), nonce, next_nonce);
return Err(TransactionError::Old);
}
Self::replace_transaction(tx, state_nonce, &mut self.current, &mut self.by_hash);
// Keep track of highest nonce stored in current
self.last_nonces.insert(address, nonce);
// But maybe there are some more items waiting in future?
// Update nonces of transactions in future
self.update_future(&address, state_nonce);
// Maybe there are some more items waiting in future?
self.move_matching_future_to_current(address, nonce + U256::one(), state_nonce);
// There might be exactly the same transaction waiting in future
// same (sender, nonce), but above function would not move it.
if let Some(order) = self.future.drop(&address, &nonce) {
// Let's insert that transaction to current (if it has higher gas_price)
let future_tx = self.by_hash.remove(&order.hash).unwrap();
Self::replace_transaction(future_tx, state_nonce, &mut self.current, &mut self.by_hash);
}
// Also enforce the limit
self.current.enforce_limit(&mut self.by_hash);
trace!(target: "miner", "status: {:?}", self.status());
Ok(())
}
/// Replaces transaction in given set (could be `future` or `current`).
@@ -540,13 +629,11 @@ impl TransactionQueue {
let new_fee = order.gas_price;
if old_fee.cmp(&new_fee) == Ordering::Greater {
// Put back old transaction since it has greater priority (higher gas_price)
set.by_address.insert(address, nonce, old);
set.insert(address, nonce, old);
// and remove new one
set.by_priority.remove(&order);
by_hash.remove(&hash);
} else {
// Make sure we remove old transaction entirely
set.by_priority.remove(&old);
by_hash.remove(&old.hash);
}
}
@@ -579,8 +666,23 @@ mod test {
new_unsigned_tx(U256::from(123)).sign(&keypair.secret())
}
fn default_nonce(_address: &Address) -> U256 {
U256::from(123)
fn default_nonce(_address: &Address) -> AccountDetails {
AccountDetails {
nonce: U256::from(123),
balance: !U256::zero()
}
}
/// Returns two transactions with identical (sender, nonce) but different hashes
fn new_similar_txs() -> (SignedTransaction, SignedTransaction) {
let keypair = KeyPair::create().unwrap();
let secret = &keypair.secret();
let nonce = U256::from(123);
let tx = new_unsigned_tx(nonce);
let mut tx2 = new_unsigned_tx(nonce);
tx2.gas_price = U256::from(2);
(tx.sign(secret), tx2.sign(secret))
}
fn new_txs(second_nonce: U256) -> (SignedTransaction, SignedTransaction) {
@@ -633,6 +735,69 @@ mod test {
assert_eq!(set.by_address.len(), 0);
}
#[test]
fn should_replace_transaction_in_set() {
let mut set = TransactionSet {
by_priority: BTreeSet::new(),
by_address: Table::new(),
limit: 1
};
// Create two transactions with same nonce
// (same hash)
let (tx1, tx2) = new_txs(U256::from(0));
let tx1 = VerifiedTransaction::new(tx1).unwrap();
let tx2 = VerifiedTransaction::new(tx2).unwrap();
let by_hash = {
let mut x = HashMap::new();
let tx1 = VerifiedTransaction::new(tx1.transaction.clone()).unwrap();
let tx2 = VerifiedTransaction::new(tx2.transaction.clone()).unwrap();
x.insert(tx1.hash(), tx1);
x.insert(tx2.hash(), tx2);
x
};
// Insert both transactions
let order1 = TransactionOrder::for_transaction(&tx1, U256::zero());
set.insert(tx1.sender(), tx1.nonce(), order1.clone());
assert_eq!(set.by_priority.len(), 1);
assert_eq!(set.by_address.len(), 1);
// Two different orders (imagine nonce changed in the meantime)
let order2 = TransactionOrder::for_transaction(&tx2, U256::one());
set.insert(tx2.sender(), tx2.nonce(), order2.clone());
assert_eq!(set.by_priority.len(), 1);
assert_eq!(set.by_address.len(), 1);
// then
assert_eq!(by_hash.len(), 1);
assert_eq!(set.by_priority.len(), 1);
assert_eq!(set.by_address.len(), 1);
assert_eq!(set.by_priority.iter().next().unwrap().clone(), order2);
}
#[test]
fn should_handle_same_transaction_imported_twice_with_different_state_nonces() {
// given
let mut txq = TransactionQueue::new();
let (tx, tx2) = new_similar_txs();
let prev_nonce = |a: &Address| AccountDetails{ nonce: default_nonce(a).nonce - U256::one(), balance:
!U256::zero() };
// First insert one transaction to future
let res = txq.add(tx, &prev_nonce);
assert!(res.is_ok());
assert_eq!(txq.status().future, 1);
// now import second transaction to current
let res = txq.add(tx2.clone(), &default_nonce);
// and then there should be only one transaction in current (the one with higher gas_price)
assert!(res.is_ok());
assert_eq!(txq.status().pending, 1);
assert_eq!(txq.status().future, 0);
assert_eq!(txq.current.by_priority.len(), 1);
assert_eq!(txq.current.by_address.len(), 1);
assert_eq!(txq.top_transactions()[0], tx2);
}
#[test]
fn should_import_tx() {
@@ -649,6 +814,56 @@ mod test {
assert_eq!(stats.pending, 1);
}
#[test]
fn gas_limit_should_never_overflow() {
// given
let mut txq = TransactionQueue::new();
txq.set_gas_limit(U256::zero());
assert_eq!(txq.gas_limit, U256::zero());
// when
txq.set_gas_limit(!U256::zero());
// then
assert_eq!(txq.gas_limit, !U256::zero());
}
#[test]
fn should_not_import_transaction_above_gas_limit() {
// given
let mut txq = TransactionQueue::new();
let tx = new_tx();
txq.set_gas_limit(tx.gas / U256::from(2));
// when
txq.add(tx, &default_nonce).unwrap_err();
// then
let stats = txq.status();
assert_eq!(stats.pending, 0);
assert_eq!(stats.future, 0);
}
#[test]
fn should_drop_transactions_from_senders_without_balance() {
// given
let mut txq = TransactionQueue::new();
let tx = new_tx();
let account = |a: &Address| AccountDetails {
nonce: default_nonce(a).nonce,
balance: U256::one()
};
// when
txq.add(tx, &account).unwrap_err();
// then
let stats = txq.status();
assert_eq!(stats.pending, 0);
assert_eq!(stats.future, 0);
}
#[test]
fn should_not_import_transaction_below_min_gas_price_threshold() {
// given
@@ -702,7 +917,7 @@ mod test {
txq.add(tx2.clone(), &default_nonce).unwrap();
// then
let top = txq.top_transactions(5);
let top = txq.top_transactions();
assert_eq!(top[0], tx);
assert_eq!(top[1], tx2);
assert_eq!(top.len(), 2);
@@ -741,7 +956,7 @@ mod test {
let stats = txq.status();
assert_eq!(stats.pending, 1);
assert_eq!(stats.future, 1);
let top = txq.top_transactions(5);
let top = txq.top_transactions();
assert_eq!(top.len(), 1);
assert_eq!(top[0], tx);
}
@@ -749,8 +964,10 @@ mod test {
#[test]
fn should_correctly_update_futures_when_removing() {
// given
let prev_nonce = |a: &Address| default_nonce(a) - U256::one();
let next2_nonce = |a: &Address| default_nonce(a) + U256::from(2);
let prev_nonce = |a: &Address| AccountDetails{ nonce: default_nonce(a).nonce - U256::one(), balance:
!U256::zero() };
let next2_nonce = |a: &Address| AccountDetails{ nonce: default_nonce(a).nonce + U256::from(2), balance:
!U256::zero() };
let mut txq = TransactionQueue::new();
@@ -866,7 +1083,7 @@ mod test {
txq.add(tx2.clone(), &default_nonce).unwrap();
// then
let t = txq.top_transactions(2);
let t = txq.top_transactions();
assert_eq!(txq.status().pending, 1);
assert_eq!(t.len(), 1);
assert_eq!(t[0], tx);
@@ -895,10 +1112,10 @@ mod test {
let mut txq = TransactionQueue::new();
let tx = new_tx();
let last_nonce = tx.nonce + U256::one();
let fetch_last_nonce = |_a: &Address| last_nonce;
let fetch_last_nonce = |_a: &Address| AccountDetails{ nonce: last_nonce, balance: !U256::zero() };
// when
txq.add(tx, &fetch_last_nonce).unwrap();
txq.add(tx, &fetch_last_nonce).unwrap_err();
// then
let stats = txq.status();
@@ -909,7 +1126,8 @@ mod test {
#[test]
fn should_not_insert_same_transaction_twice() {
// given
let nonce = |a: &Address| default_nonce(a) + U256::one();
let nonce = |a: &Address| AccountDetails { nonce: default_nonce(a).nonce + U256::one(),
balance: !U256::zero() };
let mut txq = TransactionQueue::new();
let (_tx1, tx2) = new_txs(U256::from(1));
txq.add(tx2.clone(), &default_nonce).unwrap();
@@ -917,7 +1135,7 @@ mod test {
assert_eq!(txq.status().pending, 0);
// when
txq.add(tx2.clone(), &nonce).unwrap();
txq.add(tx2.clone(), &nonce).unwrap_err();
// then
let stats = txq.status();
@@ -949,7 +1167,8 @@ mod test {
#[test]
fn should_not_move_to_future_if_state_nonce_is_higher() {
// given
let next_nonce = |a: &Address| default_nonce(a) + U256::one();
let next_nonce = |a: &Address| AccountDetails { nonce: default_nonce(a).nonce + U256::one(), balance:
!U256::zero() };
let mut txq = TransactionQueue::new();
let (tx, tx2) = new_txs(U256::from(1));
let tx3 = new_tx();
@@ -988,7 +1207,7 @@ mod test {
let stats = txq.status();
assert_eq!(stats.pending, 1);
assert_eq!(stats.future, 0);
assert_eq!(txq.top_transactions(1)[0].gas_price, U256::from(200));
assert_eq!(txq.top_transactions()[0].gas_price, U256::from(200));
}
#[test]
@@ -1018,14 +1237,16 @@ mod test {
let stats = txq.status();
assert_eq!(stats.future, 0);
assert_eq!(stats.pending, 2);
assert_eq!(txq.top_transactions(2)[1].gas_price, U256::from(200));
assert_eq!(txq.top_transactions()[1].gas_price, U256::from(200));
}
#[test]
fn should_recalculate_height_when_removing_from_future() {
// given
let previous_nonce = |a: &Address| default_nonce(a) - U256::one();
let next_nonce = |a: &Address| default_nonce(a) + U256::one();
let previous_nonce = |a: &Address| AccountDetails{ nonce: default_nonce(a).nonce - U256::one(), balance:
!U256::zero() };
let next_nonce = |a: &Address| AccountDetails{ nonce: default_nonce(a).nonce + U256::one(), balance:
!U256::zero() };
let mut txq = TransactionQueue::new();
let (tx1, tx2) = new_txs(U256::one());
txq.add(tx1.clone(), &previous_nonce).unwrap();
@@ -1040,4 +1261,29 @@ mod test {
assert_eq!(stats.future, 0);
assert_eq!(stats.pending, 1);
}
#[test]
fn should_return_none_when_transaction_from_given_address_does_not_exist() {
// given
let mut txq = TransactionQueue::new();
// then
assert_eq!(txq.last_nonce(&Address::default()), None);
}
#[test]
fn should_return_correct_nonce_when_transactions_from_given_address_exist() {
// given
let mut txq = TransactionQueue::new();
let tx = new_tx();
let from = tx.sender().unwrap();
let nonce = tx.nonce;
let details = |a: &Address| AccountDetails { nonce: nonce, balance: !U256::zero() };
// when
txq.add(tx, &details).unwrap();
// then
assert_eq!(txq.last_nonce(&from), Some(nonce));
}
}

View File

@@ -20,6 +20,7 @@
#![cfg_attr(feature="dev", feature(plugin))]
#![cfg_attr(feature="dev", plugin(clippy))]
extern crate docopt;
extern crate num_cpus;
extern crate rustc_serialize;
extern crate ethcore_util as util;
extern crate ethcore;
@@ -38,6 +39,8 @@ extern crate rpassword;
#[cfg(feature = "rpc")]
extern crate ethcore_rpc as rpc;
use std::io::{BufRead, BufReader};
use std::fs::File;
use std::net::{SocketAddr, IpAddr};
use std::env;
use std::process::exit;
@@ -46,6 +49,7 @@ use env_logger::LogBuilder;
use ctrlc::CtrlC;
use util::*;
use util::panics::{MayPanic, ForwardPanic, PanicHandler};
use util::keys::store::*;
use ethcore::spec::*;
use ethcore::client::*;
use ethcore::service::{ClientService, NetSyncMessage};
@@ -55,7 +59,8 @@ use ethminer::{Miner, MinerService};
use docopt::Docopt;
use daemonize::Daemonize;
use number_prefix::{binary_prefix, Standalone, Prefixed};
use util::keys::store::*;
#[cfg(feature = "rpc")]
use rpc::Server as RpcServer;
fn die_with_message(msg: &str) -> ! {
println!("ERROR: {}", msg);
@@ -74,7 +79,7 @@ Parity. Ethereum Client.
Usage:
parity daemon <pid-file> [options]
parity account (new | list)
parity account (new | list) [options]
parity [options]
Protocol Options:
@@ -85,9 +90,15 @@ Protocol Options:
-d --db-path PATH Specify the database & configuration directory path
[default: $HOME/.parity].
--keys-path PATH Specify the path for JSON key files to be found
[default: $HOME/.web3/keys].
[default: $HOME/.parity/keys].
--identity NAME Specify your node's name.
Account Options:
--unlock ACCOUNTS Unlock ACCOUNTS for the duration of the execution.
ACCOUNTS is a comma-delimited list of addresses.
--password FILE Provide a file containing a password for unlocking
an account.
Networking Options:
--port PORT Override the port on which the node should listen
[default: 30303].
@@ -105,8 +116,9 @@ Networking Options:
API and Console Options:
-j --jsonrpc Enable the JSON-RPC API sever.
--jsonrpc-addr HOST Specify the hostname portion of the JSONRPC API
server [default: 127.0.0.1].
--jsonrpc-interface IP Specify the hostname portion of the JSONRPC API
server, IP should be an interface's IP address, or
all (all interfaces) or local [default: local].
--jsonrpc-port PORT Specify the port portion of the JSONRPC API server
[default: 8545].
--jsonrpc-cors URL Specify CORS header for JSON-RPC API responses
@@ -149,7 +161,7 @@ Geth-compatibility Options:
--nodekey KEY Equivalent to --node-key KEY.
--nodiscover Equivalent to --no-discovery.
--rpc Equivalent to --jsonrpc.
--rpcaddr HOST Equivalent to --jsonrpc-addr HOST.
--rpcaddr IP Equivalent to --jsonrpc-interface IP.
--rpcport PORT Equivalent to --jsonrpc-port PORT.
--rpcapi APIS Equivalent to --jsonrpc-apis APIS.
--rpccorsdomain URL Equivalent to --jsonrpc-cors URL.
@@ -174,6 +186,8 @@ struct Args {
flag_chain: String,
flag_db_path: String,
flag_identity: String,
flag_unlock: Option<String>,
flag_password: Vec<String>,
flag_cache: Option<usize>,
flag_keys_path: String,
flag_bootnodes: Option<String>,
@@ -188,7 +202,7 @@ struct Args {
flag_cache_max_size: usize,
flag_queue_max_size: usize,
flag_jsonrpc: bool,
flag_jsonrpc_addr: String,
flag_jsonrpc_interface: String,
flag_jsonrpc_port: u16,
flag_jsonrpc_cors: String,
flag_jsonrpc_apis: String,
@@ -247,10 +261,10 @@ fn setup_rpc_server(
sync: Arc<EthSync>,
secret_store: Arc<AccountService>,
miner: Arc<Miner>,
url: &str,
url: &SocketAddr,
cors_domain: &str,
apis: Vec<&str>
) -> Option<Arc<PanicHandler>> {
) -> RpcServer {
use rpc::v1::*;
let server = rpc::RpcServer::new();
@@ -268,9 +282,17 @@ fn setup_rpc_server(
}
}
}
Some(server.start_http(url, cors_domain, 1))
let start_result = server.start_http(url, cors_domain);
match start_result {
Err(rpc::RpcServerError::IoError(err)) => die_with_io_error(err),
Err(e) => die!("{:?}", e),
Ok(server) => server,
}
}
#[cfg(not(feature = "rpc"))]
struct RpcServer;
#[cfg(not(feature = "rpc"))]
fn setup_rpc_server(
_client: Arc<Client>,
@@ -280,8 +302,8 @@ fn setup_rpc_server(
_url: &str,
_cors_domain: &str,
_apis: Vec<&str>
) -> Option<Arc<PanicHandler>> {
None
) -> ! {
die!("Your Parity version has been compiled without JSON-RPC support.")
}
fn print_version() {
@@ -315,8 +337,8 @@ impl Configuration {
fn author(&self) -> Address {
let d = self.args.flag_etherbase.as_ref().unwrap_or(&self.args.flag_author);
Address::from_str(d).unwrap_or_else(|_| {
die!("{}: Invalid address for --author. Must be 40 hex characters, without the 0x at the beginning.", d)
Address::from_str(clean_0x(d)).unwrap_or_else(|_| {
die!("{}: Invalid address for --author. Must be 40 hex characters, with or without the 0x at the beginning.", d)
})
}
@@ -342,7 +364,7 @@ impl Configuration {
}
}
fn _keys_path(&self) -> String {
fn keys_path(&self) -> String {
self.args.flag_keys_path.replace("$HOME", env::home_dir().unwrap().to_str().unwrap())
}
@@ -370,7 +392,7 @@ impl Configuration {
fn init_nodes(&self, spec: &Spec) -> Vec<String> {
match self.args.flag_bootnodes {
Some(ref x) if x.len() > 0 => x.split(',').map(|s| {
Some(ref x) if !x.is_empty() => x.split(',').map(|s| {
Self::normalize_enode(s).unwrap_or_else(|| {
die!("{}: Invalid node address format given for a boot node.", s)
})
@@ -409,6 +431,7 @@ impl Configuration {
ret
}
#[cfg_attr(feature="dev", allow(useless_format))]
fn client_config(&self) -> ClientConfig {
let mut client_config = ClientConfig::default();
match self.args.flag_cache {
@@ -463,7 +486,7 @@ impl Configuration {
fn execute_account_cli(&self) {
use util::keys::store::SecretStore;
use rpassword::read_password;
let mut secret_store = SecretStore::new();
let mut secret_store = SecretStore::new_in(Path::new(&self.keys_path()));
if self.args.cmd_new {
println!("Please note that password is NOT RECOVERABLE.");
println!("Type password: ");
@@ -487,6 +510,29 @@ impl Configuration {
}
}
fn account_service(&self) -> AccountService {
// Secret Store
let passwords = self.args.flag_password.iter().flat_map(|filename| {
BufReader::new(&File::open(filename).unwrap_or_else(|_| die!("{} Unable to read password file. Ensure it exists and permissions are correct.", filename)))
.lines()
.map(|l| l.unwrap())
.collect::<Vec<_>>()
.into_iter()
}).collect::<Vec<_>>();
let account_service = AccountService::new_in(Path::new(&self.keys_path()));
if let Some(ref unlocks) = self.args.flag_unlock {
for d in unlocks.split(',') {
let a = Address::from_str(clean_0x(&d)).unwrap_or_else(|_| {
die!("{}: Invalid address for --unlock. Must be 40 hex characters, without the 0x at the beginning.", d)
});
if passwords.iter().find(|p| account_service.unlock_account_no_expire(&a, p).is_ok()).is_none() {
die!("No password given to unlock account {}. Pass the password using `--password`.", a);
}
}
}
account_service
}
#[cfg_attr(feature="dev", allow(useless_format))]
fn execute_client(&self) {
// Setup panic handler
@@ -501,8 +547,14 @@ impl Configuration {
let net_settings = self.net_settings(&spec);
let sync_config = self.sync_config(&spec);
// Secret Store
let account_service = Arc::new(self.account_service());
// Build client
let mut service = ClientService::start(self.client_config(), spec, net_settings, &Path::new(&self.path())).unwrap();
let mut service = ClientService::start(
self.client_config(), spec, net_settings, &Path::new(&self.path())
).unwrap_or_else(|e| die_with_error(e));
panic_handler.forward_from(&service);
let client = service.client();
@@ -516,32 +568,32 @@ impl Configuration {
// Sync
let sync = EthSync::register(service.network(), sync_config, client.clone(), miner.clone());
// Secret Store
let account_service = Arc::new(AccountService::new());
// Setup rpc
if self.args.flag_jsonrpc || self.args.flag_rpc {
let rpc_server = if self.args.flag_jsonrpc || self.args.flag_rpc {
let apis = self.args.flag_rpcapi.as_ref().unwrap_or(&self.args.flag_jsonrpc_apis);
let url = format!("{}:{}",
self.args.flag_rpcaddr.as_ref().unwrap_or(&self.args.flag_jsonrpc_addr),
match self.args.flag_rpcaddr.as_ref().unwrap_or(&self.args.flag_jsonrpc_interface).as_str() {
"all" => "0.0.0.0",
"local" => "127.0.0.1",
x => x,
},
self.args.flag_rpcport.unwrap_or(self.args.flag_jsonrpc_port)
);
SocketAddr::from_str(&url).unwrap_or_else(|_| die!("{}: Invalid JSONRPC listen host/port given.", url));
let cors = self.args.flag_rpccorsdomain.as_ref().unwrap_or(&self.args.flag_jsonrpc_cors);
// TODO: use this as the API list.
let apis = self.args.flag_rpcapi.as_ref().unwrap_or(&self.args.flag_jsonrpc_apis);
let server_handler = setup_rpc_server(
let addr = SocketAddr::from_str(&url).unwrap_or_else(|_| die!("{}: Invalid JSONRPC listen host/port given.", url));
let cors_domain = self.args.flag_rpccorsdomain.as_ref().unwrap_or(&self.args.flag_jsonrpc_cors);
Some(setup_rpc_server(
service.client(),
sync.clone(),
account_service.clone(),
miner.clone(),
&url,
cors,
&addr,
&cors_domain,
apis.split(',').collect()
);
if let Some(handler) = server_handler {
panic_handler.forward_from(handler.deref());
}
}
))
} else {
None
};
// Register IO handler
let io_handler = Arc::new(ClientIoHandler {
@@ -553,11 +605,11 @@ impl Configuration {
service.io().register_handler(io_handler).expect("Error registering IO handler");
// Handle exit
wait_for_exit(panic_handler);
wait_for_exit(panic_handler, rpc_server);
}
}
fn wait_for_exit(panic_handler: Arc<PanicHandler>) {
fn wait_for_exit(panic_handler: Arc<PanicHandler>, _rpc_server: Option<RpcServer>) {
let exit = Arc::new(Condvar::new());
// Handle possible exits
@@ -571,6 +623,30 @@ fn wait_for_exit(panic_handler: Arc<PanicHandler>) {
// Wait for signal
let mutex = Mutex::new(());
let _ = exit.wait(mutex.lock().unwrap()).unwrap();
info!("Finishing work, please wait...");
}
fn die_with_error(e: ethcore::error::Error) -> ! {
use ethcore::error::Error;
match e {
Error::Util(UtilError::StdIo(e)) => die_with_io_error(e),
_ => die!("{:?}", e),
}
}
fn die_with_io_error(e: std::io::Error) -> ! {
match e.kind() {
std::io::ErrorKind::PermissionDenied => {
die!("No permissions to bind to specified port.")
},
std::io::ErrorKind::AddrInUse => {
die!("Specified address is already in use. Please make sure that nothing is listening on the same port or try using a different one.")
},
std::io::ErrorKind::AddrNotAvailable => {
die!("Could not use specified interface or given address is invalid.")
},
_ => die!("{:?}", e),
}
}
fn main() {

View File

@@ -1,7 +1,7 @@
[package]
description = "Ethcore jsonrpc"
name = "ethcore-rpc"
version = "1.1.0"
version = "1.0.2"
license = "GPL-3.0"
authors = ["Ethcore <admin@ethcore.io"]
build = "build.rs"
@@ -13,7 +13,7 @@ log = "0.3"
serde = "0.7.0"
serde_json = "0.7.0"
jsonrpc-core = "2.0"
jsonrpc-http-server = "3.0"
jsonrpc-http-server = { git = "https://github.com/debris/jsonrpc-http-server.git" }
ethcore-util = { path = "../util" }
ethcore = { path = "../ethcore" }
ethash = { path = "../ethash" }
@@ -22,11 +22,11 @@ ethminer = { path = "../miner" }
rustc-serialize = "0.3"
transient-hashmap = "0.1"
serde_macros = { version = "0.7.0", optional = true }
clippy = { version = "0.0.50", optional = true }
clippy = { version = "0.0.54", optional = true }
[build-dependencies]
serde_codegen = { version = "0.7.0", optional = true }
syntex = "0.29.0"
syntex = "0.30.0"
[features]
default = ["serde_codegen"]

17
rpc/rpctest/Cargo.toml Normal file
View File

@@ -0,0 +1,17 @@
[package]
description = "Rpc test client."
name = "rpctest"
version = "1.1.0"
license = "GPL-3.0"
authors = ["Ethcore <admin@ethcore.io>"]
[dependencies]
ctrlc = { git = "https://github.com/tomusdrw/rust-ctrlc.git" }
docopt = "0.6"
rustc-serialize = "0.3"
ethcore = { path = "../../ethcore" }
ethcore-devtools = { path = "../../devtools" }
ethcore-rpc = { path = ".." }
ethcore-util = { path = "../../util" }
ethjson = { path = "../../json" }
serde_json = "0.7.0"

148
rpc/rpctest/src/main.rs Normal file
View File

@@ -0,0 +1,148 @@
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
extern crate ctrlc;
extern crate docopt;
extern crate rustc_serialize;
extern crate serde_json;
extern crate ethjson;
extern crate ethcore_util as util;
extern crate ethcore;
extern crate ethcore_devtools as devtools;
extern crate ethcore_rpc as rpc;
use std::collections::HashMap;
use std::sync::{Arc, Mutex, Condvar};
use std::process;
use std::fs::File;
use std::path::Path;
use docopt::Docopt;
use ctrlc::CtrlC;
use ethcore::spec::Genesis;
use ethcore::pod_state::PodState;
use ethcore::ethereum;
use ethcore::client::{BlockChainClient, Client, ClientConfig};
use devtools::RandomTempPath;
use util::IoChannel;
use rpc::v1::tests::helpers::{TestSyncProvider, Config as SyncConfig, TestMinerService, TestAccountProvider, TestAccount};
use rpc::v1::{Eth, EthClient, EthFilter, EthFilterClient};
use util::panics::MayPanic;
use util::hash::Address;
const USAGE: &'static str = r#"
Parity rpctest client.
By Wood/Paronyan/Kotewicz/Drwięga/Volf.
Copyright 2015, 2016 Ethcore (UK) Limited
Usage:
rpctest --json <test-file> --name <test-name> [options]
rpctest --help
Options:
--jsonrpc-addr HOST Specify the hostname portion of the JSONRPC API
server [default: 127.0.0.1].
--jsonrpc-port PORT Specify the port portion of the JSONRPC API server
[default: 8545].
"#;
#[derive(Debug, RustcDecodable)]
struct Args {
arg_test_file: String,
arg_test_name: String,
flag_jsonrpc_addr: String,
flag_jsonrpc_port: u16,
}
struct Configuration {
args: Args,
}
impl Configuration {
fn parse() -> Self {
Configuration {
args: Docopt::new(USAGE).and_then(|d| d.decode()).unwrap_or_else(|e| e.exit())
}
}
fn execute(&self) {
println!("file path: {:?}", self.args.arg_test_file);
println!("test name: {:?}", self.args.arg_test_name);
let path = Path::new(&self.args.arg_test_file);
let file = File::open(path).unwrap_or_else(|_| {
println!("Cannot open file.");
process::exit(1);
});
let tests: ethjson::blockchain::Test = serde_json::from_reader(file).unwrap_or_else(|err| {
println!("Invalid json file.");
println!("{:?}", err);
process::exit(2);
});
let blockchain = tests.get(&self.args.arg_test_name).unwrap_or_else(|| {
println!("Invalid test name.");
process::exit(3);
});
let genesis = Genesis::from(blockchain.genesis());
let state = PodState::from(blockchain.pre_state.clone());
let mut spec = ethereum::new_frontier_test();
spec.set_genesis_state(state);
spec.overwrite_genesis_params(genesis);
assert!(spec.is_state_root_valid());
let temp = RandomTempPath::new();
{
let client: Arc<Client> = Client::new(ClientConfig::default(), spec, temp.as_path(), IoChannel::disconnected()).unwrap();
for b in &blockchain.blocks_rlp() {
let _ = client.import_block(b.clone());
client.flush_queue();
client.import_verified_blocks(&IoChannel::disconnected());
}
let sync = Arc::new(TestSyncProvider::new(SyncConfig {
protocol_version: 65,
num_peers: 120
}));
let miner = Arc::new(TestMinerService::default());
let mut accs = HashMap::new();
accs.insert(Address::from(1), TestAccount::new("test"));
let accounts = Arc::new(TestAccountProvider::new(accs));
let server = rpc::RpcServer::new();
server.add_delegate(EthClient::new(&client, &sync, &accounts, &miner).to_delegate());
server.add_delegate(EthFilterClient::new(&client, &miner).to_delegate());
let url = format!("{}:{}", self.args.flag_jsonrpc_addr, self.args.flag_jsonrpc_port);
let panic_handler = server.start_http(url.as_ref(), "*", 1);
let exit = Arc::new(Condvar::new());
let e = exit.clone();
CtrlC::set_handler(move || { e.notify_all(); });
let e = exit.clone();
panic_handler.on_panic(move |_reason| { e.notify_all(); });
let mutex = Mutex::new(());
let _ = exit.wait(mutex.lock().unwrap()).unwrap();
}
}
}
fn main() {
Configuration::parse().execute();
}

View File

@@ -33,10 +33,10 @@ extern crate ethminer;
extern crate transient_hashmap;
use std::sync::Arc;
use std::thread;
use util::panics::PanicHandler;
use std::net::SocketAddr;
use self::jsonrpc_core::{IoHandler, IoDelegate};
pub use jsonrpc_http_server::{Server, RpcServerError};
pub mod v1;
/// Http server.
@@ -45,7 +45,7 @@ pub struct RpcServer {
}
impl RpcServer {
/// Construct new http server object with given number of threads.
/// Construct new http server object.
pub fn new() -> RpcServer {
RpcServer {
handler: Arc::new(IoHandler::new()),
@@ -57,18 +57,9 @@ impl RpcServer {
self.handler.add_delegate(delegate);
}
/// Start server asynchronously in new thread and returns panic handler.
pub fn start_http(&self, addr: &str, cors_domain: &str, threads: usize) -> Arc<PanicHandler> {
let addr = addr.to_owned();
/// Start server asynchronously and returns result with `Server` handle on success or an error.
pub fn start_http(&self, addr: &SocketAddr, cors_domain: &str) -> Result<Server, RpcServerError> {
let cors_domain = cors_domain.to_owned();
let panic_handler = PanicHandler::new_in_arc();
let ph = panic_handler.clone();
let server = jsonrpc_http_server::Server::new(self.handler.clone());
thread::Builder::new().name("jsonrpc_http".to_string()).spawn(move || {
ph.catch_panic(move || {
server.start(addr.as_ref(), jsonrpc_http_server::AccessControlAllowOrigin::Value(cors_domain), threads);
}).unwrap()
}).expect("Error while creating jsonrpc http thread");
panic_handler
Server::start(addr, self.handler.clone(), jsonrpc_http_server::AccessControlAllowOrigin::Value(cors_domain))
}
}

View File

@@ -61,7 +61,6 @@ impl<F, T> PollManager<F, T> where T: Timer {
}
// Implementation is always using `poll_mut`
#[cfg(test)]
/// Get a reference to stored poll filter
pub fn poll(&mut self, id: &PollId) -> Option<&F> {
self.polls.prune();

View File

@@ -19,21 +19,29 @@ use std::collections::HashSet;
use std::sync::{Arc, Weak, Mutex};
use std::ops::Deref;
use ethsync::{SyncProvider, SyncState};
use ethminer::{MinerService};
use ethminer::{MinerService, AccountDetails};
use jsonrpc_core::*;
use util::numbers::*;
use util::sha3::*;
use util::rlp::encode;
use util::rlp::{encode, UntrustedRlp, View};
use ethcore::client::*;
use ethcore::block::IsBlock;
use ethcore::views::*;
use ethcore::ethereum::Ethash;
use ethcore::ethereum::denominations::shannon;
use ethcore::transaction::Transaction as EthTransaction;
use ethcore::transaction::{Transaction as EthTransaction, SignedTransaction, Action};
use v1::traits::{Eth, EthFilter};
use v1::types::{Block, BlockTransactions, BlockNumber, Bytes, SyncStatus, SyncInfo, Transaction, TransactionRequest, OptionalValue, Index, Filter, Log};
use v1::types::{Block, BlockTransactions, BlockNumber, Bytes, SyncStatus, SyncInfo, Transaction, TransactionRequest, CallRequest, OptionalValue, Index, Filter, Log, Receipt};
use v1::helpers::{PollFilter, PollManager, ExternalMinerService, ExternalMiner};
use util::keys::store::AccountProvider;
use serde;
fn default_gas() -> U256 {
U256::from(21_000)
}
fn default_call_gas() -> U256 {
U256::from(50_000_000)
}
/// Eth rpc implementation.
pub struct EthClient<C, S, A, M, EM = ExternalMiner>
@@ -61,7 +69,6 @@ impl<C, S, A, M> EthClient<C, S, A, M, ExternalMiner>
}
}
impl<C, S, A, M, EM> EthClient<C, S, A, M, EM>
where C: BlockChainClient,
S: SyncProvider,
@@ -103,7 +110,8 @@ impl<C, S, A, M, EM> EthClient<C, S, A, M, EM>
timestamp: U256::from(view.timestamp()),
difficulty: view.difficulty(),
total_difficulty: total_difficulty,
uncles: vec![],
nonce: view.seal().get(1).map_or_else(H64::zero, |r| H64::from_slice(r)),
uncles: block_view.uncle_hashes(),
transactions: {
if include_txs {
BlockTransactions::Full(block_view.localized_transactions().into_iter().map(From::from).collect())
@@ -111,7 +119,7 @@ impl<C, S, A, M, EM> EthClient<C, S, A, M, EM>
BlockTransactions::Hashes(block_view.transaction_hashes())
}
},
extra_data: Bytes::default()
extra_data: Bytes::new(view.extra_data())
};
to_value(&block)
},
@@ -126,9 +134,95 @@ impl<C, S, A, M, EM> EthClient<C, S, A, M, EM>
}
}
fn uncle(&self, _block: BlockId, _index: usize) -> Result<Value, Error> {
// TODO: implement!
Ok(Value::Null)
fn uncle(&self, id: UncleId) -> Result<Value, Error> {
let client = take_weak!(self.client);
match client.uncle(id).and_then(|u| client.block_total_difficulty(BlockId::Hash(u.hash())).map(|diff| (diff, u))) {
Some((difficulty, uncle)) => {
let block = Block {
hash: OptionalValue::Value(uncle.hash()),
parent_hash: uncle.parent_hash,
uncles_hash: uncle.uncles_hash,
author: uncle.author,
miner: uncle.author,
state_root: uncle.state_root,
transactions_root: uncle.transactions_root,
number: OptionalValue::Value(U256::from(uncle.number)),
gas_used: uncle.gas_used,
gas_limit: uncle.gas_limit,
logs_bloom: uncle.log_bloom,
timestamp: U256::from(uncle.timestamp),
difficulty: uncle.difficulty,
total_difficulty: difficulty,
receipts_root: uncle.receipts_root,
extra_data: Bytes::new(uncle.extra_data),
// todo:
nonce: H64::from(0),
uncles: vec![],
transactions: BlockTransactions::Hashes(vec![]),
};
to_value(&block)
},
None => Ok(Value::Null)
}
}
fn sign_call(&self, request: CallRequest) -> Result<SignedTransaction, Error> {
let client = take_weak!(self.client);
let miner = take_weak!(self.miner);
let from = request.from.unwrap_or(Address::zero());
Ok(EthTransaction {
nonce: request.nonce.unwrap_or_else(|| client.nonce(&from)),
action: request.to.map_or(Action::Create, Action::Call),
gas: request.gas.unwrap_or_else(default_call_gas),
gas_price: request.gas_price.unwrap_or_else(|| miner.sensible_gas_price()),
value: request.value.unwrap_or_else(U256::zero),
data: request.data.map_or_else(Vec::new, |d| d.to_vec())
}.fake_sign(from))
}
fn dispatch_transaction(&self, signed_transaction: SignedTransaction) -> Result<Value, Error> {
let hash = signed_transaction.hash();
let import = {
let client = take_weak!(self.client);
take_weak!(self.miner).import_transactions(vec![signed_transaction], |a: &Address| AccountDetails {
nonce: client.nonce(a),
balance: client.balance(a),
})
};
match import.into_iter().collect::<Result<Vec<_>, _>>() {
Ok(_) => {
to_value(&hash)
}
Err(e) => {
warn!("Error sending transaction: {:?}", e);
to_value(&H256::zero())
}
}
}
}
const MAX_QUEUE_SIZE_TO_MINE_ON: usize = 4; // because uncles go back 6.
fn params_len(params: &Params) -> usize {
match params {
&Params::Array(ref vec) => vec.len(),
_ => 0,
}
}
fn from_params_discard_second<F>(params: Params) -> Result<(F,), Error> where F: serde::de::Deserialize {
match params_len(&params) {
1 => from_params::<(F, )>(params),
_ => from_params::<(F, BlockNumber)>(params).map(|(f, _block_number)| (f, )),
}
}
fn from_params_discard_third<F1, F2>(params: Params) -> Result<(F1, F2,), Error> where F1: serde::de::Deserialize, F2: serde::de::Deserialize {
match params_len(&params) {
2 => from_params::<(F1, F2, )>(params),
_ => from_params::<(F1, F2, BlockNumber)>(params).map(|(f1, f2, _block_number)| (f1, f2, )),
}
}
@@ -167,8 +261,8 @@ impl<C, S, A, M, EM> Eth for EthClient<C, S, A, M, EM>
// TODO: do not hardcode author.
fn author(&self, params: Params) -> Result<Value, Error> {
match params {
Params::None => to_value(&Address::new()),
_ => Err(Error::invalid_params())
Params::None => to_value(&take_weak!(self.miner).author()),
_ => Err(Error::invalid_params()),
}
}
@@ -190,7 +284,7 @@ impl<C, S, A, M, EM> Eth for EthClient<C, S, A, M, EM>
fn gas_price(&self, params: Params) -> Result<Value, Error> {
match params {
Params::None => to_value(&(shannon() * U256::from(50))),
Params::None => to_value(&take_weak!(self.miner).sensible_gas_price()),
_ => Err(Error::invalid_params())
}
}
@@ -211,58 +305,58 @@ impl<C, S, A, M, EM> Eth for EthClient<C, S, A, M, EM>
}
fn balance(&self, params: Params) -> Result<Value, Error> {
from_params::<(Address, BlockNumber)>(params)
.and_then(|(address, _block_number)| to_value(&take_weak!(self.client).balance(&address)))
from_params_discard_second(params).and_then(|(address, )|
to_value(&take_weak!(self.client).balance(&address)))
}
fn storage_at(&self, params: Params) -> Result<Value, Error> {
from_params::<(Address, U256, BlockNumber)>(params)
.and_then(|(address, position, _block_number)|
to_value(&U256::from(take_weak!(self.client).storage_at(&address, &H256::from(position)))))
from_params_discard_third::<Address, U256>(params).and_then(|(address, position, )|
to_value(&U256::from(take_weak!(self.client).storage_at(&address, &H256::from(position)))))
}
fn transaction_count(&self, params: Params) -> Result<Value, Error> {
from_params::<(Address, BlockNumber)>(params)
.and_then(|(address, _block_number)| to_value(&take_weak!(self.client).nonce(&address)))
from_params_discard_second(params).and_then(|(address, )|
to_value(&take_weak!(self.client).nonce(&address)))
}
fn block_transaction_count_by_hash(&self, params: Params) -> Result<Value, Error> {
from_params::<(H256,)>(params)
.and_then(|(hash,)| // match
to_value(&take_weak!(self.client).block(BlockId::Hash(hash))
.map_or_else(U256::zero, |bytes| U256::from(BlockView::new(&bytes).transactions_count()))))
take_weak!(self.client).block(BlockId::Hash(hash))
.map_or(Ok(Value::Null), |bytes| to_value(&U256::from(BlockView::new(&bytes).transactions_count()))))
}
fn block_transaction_count_by_number(&self, params: Params) -> Result<Value, Error> {
from_params::<(BlockNumber,)>(params)
.and_then(|(block_number,)| match block_number {
BlockNumber::Pending => to_value(&U256::from(take_weak!(self.miner).status().transaction_queue_pending)),
_ => to_value(&take_weak!(self.client).block(block_number.into())
.map_or_else(U256::zero, |bytes| U256::from(BlockView::new(&bytes).transactions_count())))
BlockNumber::Pending => to_value(
&U256::from(take_weak!(self.miner).status().transactions_in_pending_block)
),
_ => take_weak!(self.client).block(block_number.into())
.map_or(Ok(Value::Null), |bytes| to_value(&U256::from(BlockView::new(&bytes).transactions_count())))
})
}
fn block_uncles_count_by_hash(&self, params: Params) -> Result<Value, Error> {
from_params::<(H256,)>(params)
.and_then(|(hash,)|
to_value(&take_weak!(self.client).block(BlockId::Hash(hash))
.map_or_else(U256::zero, |bytes| U256::from(BlockView::new(&bytes).uncles_count()))))
take_weak!(self.client).block(BlockId::Hash(hash))
.map_or(Ok(Value::Null), |bytes| to_value(&U256::from(BlockView::new(&bytes).uncles_count()))))
}
fn block_uncles_count_by_number(&self, params: Params) -> Result<Value, Error> {
from_params::<(BlockNumber,)>(params)
.and_then(|(block_number,)| match block_number {
BlockNumber::Pending => to_value(&U256::from(0)),
_ => to_value(&take_weak!(self.client).block(block_number.into())
.map_or_else(U256::zero, |bytes| U256::from(BlockView::new(&bytes).uncles_count())))
_ => take_weak!(self.client).block(block_number.into())
.map_or(Ok(Value::Null), |bytes| to_value(&U256::from(BlockView::new(&bytes).uncles_count())))
})
}
// TODO: do not ignore block number param
fn code_at(&self, params: Params) -> Result<Value, Error> {
from_params::<(Address, BlockNumber)>(params)
.and_then(|(address, _block_number)|
to_value(&take_weak!(self.client).code(&address).map_or_else(Bytes::default, Bytes::new)))
from_params_discard_second(params).and_then(|(address, )|
to_value(&take_weak!(self.client).code(&address).map_or_else(Bytes::default, Bytes::new)))
}
fn block_by_hash(&self, params: Params) -> Result<Value, Error> {
@@ -277,7 +371,13 @@ impl<C, S, A, M, EM> Eth for EthClient<C, S, A, M, EM>
fn transaction_by_hash(&self, params: Params) -> Result<Value, Error> {
from_params::<(H256,)>(params)
.and_then(|(hash,)| self.transaction(TransactionId::Hash(hash)))
.and_then(|(hash,)| {
let miner = take_weak!(self.miner);
match miner.transaction(&hash) {
Some(pending_tx) => to_value(&Transaction::from(pending_tx)),
None => self.transaction(TransactionId::Hash(hash))
}
})
}
fn transaction_by_block_hash_and_index(&self, params: Params) -> Result<Value, Error> {
@@ -290,14 +390,23 @@ impl<C, S, A, M, EM> Eth for EthClient<C, S, A, M, EM>
.and_then(|(number, index)| self.transaction(TransactionId::Location(number.into(), index.value())))
}
fn transaction_receipt(&self, params: Params) -> Result<Value, Error> {
from_params::<(H256,)>(params)
.and_then(|(hash,)| {
let client = take_weak!(self.client);
let receipt = client.transaction_receipt(TransactionId::Hash(hash));
to_value(&receipt.map(Receipt::from))
})
}
fn uncle_by_block_hash_and_index(&self, params: Params) -> Result<Value, Error> {
from_params::<(H256, Index)>(params)
.and_then(|(hash, index)| self.uncle(BlockId::Hash(hash), index.value()))
.and_then(|(hash, index)| self.uncle(UncleId(BlockId::Hash(hash), index.value())))
}
fn uncle_by_block_number_and_index(&self, params: Params) -> Result<Value, Error> {
from_params::<(BlockNumber, Index)>(params)
.and_then(|(number, index)| self.uncle(number.into(), index.value()))
.and_then(|(number, index)| self.uncle(UncleId(number.into(), index.value())))
}
fn compilers(&self, params: Params) -> Result<Value, Error> {
@@ -321,6 +430,17 @@ impl<C, S, A, M, EM> Eth for EthClient<C, S, A, M, EM>
fn work(&self, params: Params) -> Result<Value, Error> {
match params {
Params::None => {
let client = take_weak!(self.client);
// check if we're still syncing and return empty strings in that case
{
//TODO: check if initial sync is complete here
//let sync = take_weak!(self.sync);
if /*sync.status().state != SyncState::Idle ||*/ client.queue_info().total_queue_size() > MAX_QUEUE_SIZE_TO_MINE_ON {
trace!(target: "miner", "Syncing. Cannot give any work.");
return to_value(&(String::new(), String::new(), String::new()));
}
}
let miner = take_weak!(self.miner);
let client = take_weak!(self.client);
let u = miner.sealing_block(client.deref()).lock().unwrap();
@@ -331,7 +451,7 @@ impl<C, S, A, M, EM> Eth for EthClient<C, S, A, M, EM>
let seed_hash = Ethash::get_seedhash(b.block().header().number());
to_value(&(pow_hash, seed_hash, target))
}
_ => Err(Error::invalid_params())
_ => Err(Error::internal_error())
}
},
_ => Err(Error::invalid_params())
@@ -340,7 +460,7 @@ impl<C, S, A, M, EM> Eth for EthClient<C, S, A, M, EM>
fn submit_work(&self, params: Params) -> Result<Value, Error> {
from_params::<(H64, H256, H256)>(params).and_then(|(nonce, pow_hash, mix_hash)| {
// trace!("Decoded: nonce={}, pow_hash={}, mix_hash={}", nonce, pow_hash, mix_hash);
trace!(target: "miner", "submit_work: Decoded: nonce={}, pow_hash={}, mix_hash={}", nonce, pow_hash, mix_hash);
let miner = take_weak!(self.miner);
let client = take_weak!(self.client);
let seal = vec![encode(&mix_hash).to_vec(), encode(&nonce).to_vec()];
@@ -350,7 +470,6 @@ impl<C, S, A, M, EM> Eth for EthClient<C, S, A, M, EM>
}
fn submit_hashrate(&self, params: Params) -> Result<Value, Error> {
// TODO: Index should be U256.
from_params::<(U256, H256)>(params).and_then(|(rate, id)| {
self.external_miner.submit_hashrate(rate, id);
to_value(&true)
@@ -359,30 +478,61 @@ impl<C, S, A, M, EM> Eth for EthClient<C, S, A, M, EM>
fn send_transaction(&self, params: Params) -> Result<Value, Error> {
from_params::<(TransactionRequest, )>(params)
.and_then(|(transaction_request, )| {
.and_then(|(request, )| {
let accounts = take_weak!(self.accounts);
match accounts.account_secret(&transaction_request.from) {
match accounts.account_secret(&request.from) {
Ok(secret) => {
let miner = take_weak!(self.miner);
let client = take_weak!(self.client);
let transaction: EthTransaction = transaction_request.into();
let signed_transaction = transaction.sign(&secret);
let hash = signed_transaction.hash();
let import = miner.import_transactions(vec![signed_transaction], |a: &Address| client.nonce(a));
match import {
Ok(_) => to_value(&hash),
Err(e) => {
warn!("Error sending transaction: {:?}", e);
to_value(&U256::zero())
}
}
let signed_transaction = {
let client = take_weak!(self.client);
let miner = take_weak!(self.miner);
EthTransaction {
nonce: request.nonce
.or_else(|| miner
.last_nonce(&request.from)
.map(|nonce| nonce + U256::one()))
.unwrap_or_else(|| client.nonce(&request.from)),
action: request.to.map_or(Action::Create, Action::Call),
gas: request.gas.unwrap_or_else(default_gas),
gas_price: request.gas_price.unwrap_or_else(|| miner.sensible_gas_price()),
value: request.value.unwrap_or_else(U256::zero),
data: request.data.map_or_else(Vec::new, |d| d.to_vec()),
}.sign(&secret)
};
self.dispatch_transaction(signed_transaction)
},
Err(_) => { to_value(&U256::zero()) }
Err(_) => { to_value(&H256::zero()) }
}
})
}
fn send_raw_transaction(&self, params: Params) -> Result<Value, Error> {
from_params::<(Bytes, )>(params)
.and_then(|(raw_transaction, )| {
let raw_transaction = raw_transaction.to_vec();
match UntrustedRlp::new(&raw_transaction).as_val() {
Ok(signed_transaction) => self.dispatch_transaction(signed_transaction),
Err(_) => to_value(&H256::zero()),
}
})
}
fn call(&self, params: Params) -> Result<Value, Error> {
from_params_discard_second(params).and_then(|(request, )| {
let signed = try!(self.sign_call(request));
let client = take_weak!(self.client);
let output = client.call(&signed).map(|e| Bytes(e.output)).unwrap_or(Bytes::new(vec![]));
to_value(&output)
})
}
fn estimate_gas(&self, params: Params) -> Result<Value, Error> {
from_params_discard_second(params).and_then(|(request, )| {
let signed = try!(self.sign_call(request));
let client = take_weak!(self.client);
let used = client.call(&signed).map(|res| res.gas_used + res.refunded).unwrap_or(From::from(0));
to_value(&used)
})
}
}
/// Eth filter rpc implementation.
@@ -481,10 +631,11 @@ impl<C, M> EthFilter for EthFilterClient<C, M>
to_value(&diff)
},
PollFilter::Logs(ref mut block_number, ref mut filter) => {
PollFilter::Logs(ref mut block_number, ref filter) => {
let mut filter = filter.clone();
filter.from_block = BlockId::Number(*block_number);
filter.to_block = BlockId::Latest;
let logs = client.logs(filter.clone())
let logs = client.logs(filter)
.into_iter()
.map(From::from)
.collect::<Vec<Log>>();
@@ -499,6 +650,24 @@ impl<C, M> EthFilter for EthFilterClient<C, M>
})
}
fn filter_logs(&self, params: Params) -> Result<Value, Error> {
from_params::<(Index,)>(params)
.and_then(|(index,)| {
let mut polls = self.polls.lock().unwrap();
match polls.poll(&index.value()) {
Some(&PollFilter::Logs(ref _block_number, ref filter)) => {
let logs = take_weak!(self.client).logs(filter.clone())
.into_iter()
.map(From::from)
.collect::<Vec<Log>>();
to_value(&logs)
},
// just empty array
_ => Ok(Value::Array(vec![] as Vec<Value>)),
}
})
}
fn uninstall_filter(&self, params: Params) -> Result<Value, Error> {
from_params::<(Index,)>(params)
.and_then(|(index,)| {

View File

@@ -36,7 +36,7 @@ impl<S> NetClient<S> where S: SyncProvider {
impl<S> Net for NetClient<S> where S: SyncProvider + 'static {
fn version(&self, _: Params) -> Result<Value, Error> {
Ok(Value::String(format!("{}", take_weak!(self.sync).status().protocol_version).to_owned()))
Ok(Value::String(format!("{}", take_weak!(self.sync).status().network_id).to_owned()))
}
fn peer_count(&self, _params: Params) -> Result<Value, Error> {

View File

@@ -49,7 +49,7 @@ impl<A> Personal for PersonalClient<A> where A: AccountProvider + 'static {
|(pass, )| {
let store = take_weak!(self.accounts);
match store.new_account(&pass) {
Ok(address) => Ok(Value::String(format!("0x{:?}", address))),
Ok(address) => to_value(&address),
Err(_) => Err(Error::internal_error())
}
}

View File

@@ -18,6 +18,8 @@
use jsonrpc_core::*;
use util::version;
use v1::traits::Web3;
use v1::types::Bytes;
use util::sha3::Hashable;
/// Web3 rpc implementation.
pub struct Web3Client;
@@ -34,4 +36,14 @@ impl Web3 for Web3Client {
_ => Err(Error::invalid_params())
}
}
fn sha3(&self, params: Params) -> Result<Value, Error> {
from_params::<(Bytes,)>(params).and_then(
|(data,)| {
let Bytes(ref v) = data;
let sha3 = v.sha3();
to_value(&sha3)
}
)
}
}

View File

@@ -23,8 +23,7 @@ mod impls;
mod types;
mod helpers;
#[cfg(test)]
mod tests;
pub mod tests;
pub use self::traits::{Web3, Eth, EthFilter, Personal, Net};
pub use self::impls::*;

View File

@@ -14,12 +14,16 @@
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::str::FromStr;
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use jsonrpc_core::IoHandler;
use util::hash::{Address, H256};
use util::numbers::U256;
use ethcore::client::{TestBlockChainClient, EachBlockWith};
use util::hash::{Address, H256, FixedHash};
use util::numbers::{Uint, U256};
use ethcore::client::{TestBlockChainClient, EachBlockWith, Executed, TransactionId};
use ethcore::log_entry::{LocalizedLogEntry, LogEntry};
use ethcore::receipt::LocalizedReceipt;
use ethcore::transaction::{Transaction, Action};
use v1::{Eth, EthClient};
use v1::tests::helpers::{TestAccount, TestAccountProvider, TestSyncProvider, Config, TestMinerService, TestExternalMiner};
@@ -37,20 +41,20 @@ fn accounts_provider() -> Arc<TestAccountProvider> {
fn sync_provider() -> Arc<TestSyncProvider> {
Arc::new(TestSyncProvider::new(Config {
protocol_version: 65,
network_id: From::from(3),
num_peers: 120,
}))
}
fn miner_service() -> Arc<TestMinerService> {
Arc::new(TestMinerService)
Arc::new(TestMinerService::default())
}
struct EthTester {
client: Arc<TestBlockChainClient>,
_sync: Arc<TestSyncProvider>,
_accounts_provider: Arc<TestAccountProvider>,
_miner: Arc<TestMinerService>,
pub client: Arc<TestBlockChainClient>,
pub sync: Arc<TestSyncProvider>,
pub accounts_provider: Arc<TestAccountProvider>,
miner: Arc<TestMinerService>,
hashrates: Arc<RwLock<HashMap<H256, U256>>>,
pub io: IoHandler,
}
@@ -68,9 +72,9 @@ impl Default for EthTester {
io.add_delegate(eth);
EthTester {
client: client,
_sync: sync,
_accounts_provider: ap,
_miner: miner,
sync: sync,
accounts_provider: ap,
miner: miner,
io: io,
hashrates: hashrates,
}
@@ -80,7 +84,7 @@ impl Default for EthTester {
#[test]
fn rpc_eth_protocol_version() {
let request = r#"{"jsonrpc": "2.0", "method": "eth_protocolVersion", "params": [], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":"65","id":1}"#;
let response = r#"{"jsonrpc":"2.0","result":"63","id":1}"#;
assert_eq!(EthTester::default().io.handle_request(request), Some(response.to_owned()));
}
@@ -147,7 +151,7 @@ fn rpc_eth_mining() {
#[test]
fn rpc_eth_gas_price() {
let request = r#"{"jsonrpc": "2.0", "method": "eth_gasPrice", "params": [], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":"0x0ba43b7400","id":1}"#;
let response = r#"{"jsonrpc":"2.0","result":"0x04a817c800","id":1}"#;
assert_eq!(EthTester::default().io.handle_request(request), Some(response.to_owned()));
}
@@ -224,7 +228,7 @@ fn rpc_eth_block_transaction_count_by_hash() {
"params": ["0xb903239f8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238"],
"id": 1
}"#;
let response = r#"{"jsonrpc":"2.0","result":"0x00","id":1}"#;
let response = r#"{"jsonrpc":"2.0","result":null,"id":1}"#;
assert_eq!(EthTester::default().io.handle_request(request), Some(response.to_owned()));
}
@@ -242,6 +246,41 @@ fn rpc_eth_transaction_count_by_number() {
assert_eq!(EthTester::default().io.handle_request(request), Some(response.to_owned()));
}
#[test]
fn rpc_eth_transaction_count_by_number_pending() {
let request = r#"{
"jsonrpc": "2.0",
"method": "eth_getBlockTransactionCountByNumber",
"params": ["pending"],
"id": 1
}"#;
let response = r#"{"jsonrpc":"2.0","result":"0x01","id":1}"#;
assert_eq!(EthTester::default().io.handle_request(request), Some(response.to_owned()));
}
#[test]
fn rpc_eth_pending_transaction_by_hash() {
use util::*;
use ethcore::transaction::*;
let tester = EthTester::default();
{
let tx: SignedTransaction = decode(&FromHex::from_hex("f85f800182520894095e7baea6a6c7c4c2dfeb977efac326af552d870a801ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804").unwrap());
tester.miner.pending_transactions.lock().unwrap().insert(H256::zero(), tx);
}
let response = r#"{"jsonrpc":"2.0","result":{"blockHash":null,"blockNumber":null,"from":"0x0f65fe9276bc9a24ae7083ae28e2660ef72df99e","gas":"0x5208","gasPrice":"0x01","hash":"0x41df922fd0d4766fcc02e161f8295ec28522f329ae487f14d811e4b64c8d6e31","input":"0x","nonce":"0x00","to":"0x095e7baea6a6c7c4c2dfeb977efac326af552d87","transactionIndex":null,"value":"0x0a"},"id":1}"#;
let request = r#"{
"jsonrpc": "2.0",
"method": "eth_getTransactionByHash",
"params": ["0x0000000000000000000000000000000000000000000000000000000000000000"],
"id": 1
}"#;
assert_eq!(tester.io.handle_request(request), Some(response.to_owned()));
}
#[test]
fn rpc_eth_uncle_count_by_block_hash() {
let request = r#"{
@@ -250,7 +289,7 @@ fn rpc_eth_uncle_count_by_block_hash() {
"params": ["0xb903239f8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238"],
"id": 1
}"#;
let response = r#"{"jsonrpc":"2.0","result":"0x00","id":1}"#;
let response = r#"{"jsonrpc":"2.0","result":null,"id":1}"#;
assert_eq!(EthTester::default().io.handle_request(request), Some(response.to_owned()));
}
@@ -285,15 +324,179 @@ fn rpc_eth_code() {
}
#[test]
#[ignore]
fn rpc_eth_call() {
unimplemented!()
let tester = EthTester::default();
tester.client.set_execution_result(Executed {
gas: U256::zero(),
gas_used: U256::from(0xff30),
refunded: U256::from(0x5),
cumulative_gas_used: U256::zero(),
logs: vec![],
contracts_created: vec![],
output: vec![0x12, 0x34, 0xff],
});
let request = r#"{
"jsonrpc": "2.0",
"method": "eth_call",
"params": [{
"from": "0xb60e8dd61c5d32be8058bb8eb970870f07233155",
"to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567",
"gas": "0x76c0",
"gasPrice": "0x9184e72a000",
"value": "0x9184e72a",
"data": "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675"
},
"latest"],
"id": 1
}"#;
let response = r#"{"jsonrpc":"2.0","result":"0x1234ff","id":1}"#;
assert_eq!(tester.io.handle_request(request), Some(response.to_owned()));
}
#[test]
fn rpc_eth_call_default_block() {
let tester = EthTester::default();
tester.client.set_execution_result(Executed {
gas: U256::zero(),
gas_used: U256::from(0xff30),
refunded: U256::from(0x5),
cumulative_gas_used: U256::zero(),
logs: vec![],
contracts_created: vec![],
output: vec![0x12, 0x34, 0xff],
});
let request = r#"{
"jsonrpc": "2.0",
"method": "eth_call",
"params": [{
"from": "0xb60e8dd61c5d32be8058bb8eb970870f07233155",
"to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567",
"gas": "0x76c0",
"gasPrice": "0x9184e72a000",
"value": "0x9184e72a",
"data": "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675"
}],
"id": 1
}"#;
let response = r#"{"jsonrpc":"2.0","result":"0x1234ff","id":1}"#;
assert_eq!(tester.io.handle_request(request), Some(response.to_owned()));
}
#[test]
fn rpc_eth_estimate_gas() {
let tester = EthTester::default();
tester.client.set_execution_result(Executed {
gas: U256::zero(),
gas_used: U256::from(0xff30),
refunded: U256::from(0x5),
cumulative_gas_used: U256::zero(),
logs: vec![],
contracts_created: vec![],
output: vec![0x12, 0x34, 0xff],
});
let request = r#"{
"jsonrpc": "2.0",
"method": "eth_estimateGas",
"params": [{
"from": "0xb60e8dd61c5d32be8058bb8eb970870f07233155",
"to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567",
"gas": "0x76c0",
"gasPrice": "0x9184e72a000",
"value": "0x9184e72a",
"data": "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675"
},
"latest"],
"id": 1
}"#;
let response = r#"{"jsonrpc":"2.0","result":"0xff35","id":1}"#;
assert_eq!(tester.io.handle_request(request), Some(response.to_owned()));
}
#[test]
fn rpc_eth_estimate_gas_default_block() {
let tester = EthTester::default();
tester.client.set_execution_result(Executed {
gas: U256::zero(),
gas_used: U256::from(0xff30),
refunded: U256::from(0x5),
cumulative_gas_used: U256::zero(),
logs: vec![],
contracts_created: vec![],
output: vec![0x12, 0x34, 0xff],
});
let request = r#"{
"jsonrpc": "2.0",
"method": "eth_estimateGas",
"params": [{
"from": "0xb60e8dd61c5d32be8058bb8eb970870f07233155",
"to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567",
"gas": "0x76c0",
"gasPrice": "0x9184e72a000",
"value": "0x9184e72a",
"data": "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675"
}],
"id": 1
}"#;
let response = r#"{"jsonrpc":"2.0","result":"0xff35","id":1}"#;
assert_eq!(tester.io.handle_request(request), Some(response.to_owned()));
}
#[test]
#[ignore]
fn rpc_eth_send_transaction() {
unimplemented!()
let account = TestAccount::new("123");
let address = account.address();
let secret = account.secret.clone();
let tester = EthTester::default();
tester.accounts_provider.accounts.write().unwrap().insert(address.clone(), account);
let request = r#"{
"jsonrpc": "2.0",
"method": "eth_sendTransaction",
"params": [{
"from": ""#.to_owned() + format!("0x{:?}", address).as_ref() + r#"",
"to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567",
"gas": "0x76c0",
"gasPrice": "0x9184e72a000",
"value": "0x9184e72a"
}],
"id": 1
}"#;
let t = Transaction {
nonce: U256::zero(),
gas_price: U256::from(0x9184e72a000u64),
gas: U256::from(0x76c0),
action: Action::Call(Address::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap()),
value: U256::from(0x9184e72au64),
data: vec![]
}.sign(&secret);
let response = r#"{"jsonrpc":"2.0","result":""#.to_owned() + format!("0x{:?}", t.hash()).as_ref() + r#"","id":1}"#;
assert_eq!(tester.io.handle_request(request.as_ref()), Some(response));
tester.miner.last_nonces.write().unwrap().insert(address.clone(), U256::zero());
let t = Transaction {
nonce: U256::one(),
gas_price: U256::from(0x9184e72a000u64),
gas: U256::from(0x76c0),
action: Action::Call(Address::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap()),
value: U256::from(0x9184e72au64),
data: vec![]
}.sign(&secret);
let response = r#"{"jsonrpc":"2.0","result":""#.to_owned() + format!("0x{:?}", t.hash()).as_ref() + r#"","id":1}"#;
assert_eq!(tester.io.handle_request(request.as_ref()), Some(response));
}
#[test]
@@ -309,9 +512,60 @@ fn rpc_eth_sign() {
}
#[test]
#[ignore]
fn rpc_eth_estimate_gas() {
unimplemented!()
fn rpc_eth_transaction_receipt() {
let receipt = LocalizedReceipt {
transaction_hash: H256::zero(),
transaction_index: 0,
block_hash: H256::from_str("ed76641c68a1c641aee09a94b3b471f4dc0316efe5ac19cf488e2674cf8d05b5").unwrap(),
block_number: 0x4510c,
cumulative_gas_used: U256::from(0x20),
gas_used: U256::from(0x10),
contract_address: None,
logs: vec![LocalizedLogEntry {
entry: LogEntry {
address: Address::from_str("33990122638b9132ca29c723bdf037f1a891a70c").unwrap(),
topics: vec![
H256::from_str("a6697e974e6a320f454390be03f74955e8978f1a6971ea6730542e37b66179bc").unwrap(),
H256::from_str("4861736852656700000000000000000000000000000000000000000000000000").unwrap()
],
data: vec![],
},
block_hash: H256::from_str("ed76641c68a1c641aee09a94b3b471f4dc0316efe5ac19cf488e2674cf8d05b5").unwrap(),
block_number: 0x4510c,
transaction_hash: H256::new(),
transaction_index: 0,
log_index: 1,
}]
};
let hash = H256::from_str("b903239f8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238").unwrap();
let tester = EthTester::default();
tester.client.set_transaction_receipt(TransactionId::Hash(hash), receipt);
let request = r#"{
"jsonrpc": "2.0",
"method": "eth_getTransactionReceipt",
"params": ["0xb903239f8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238"],
"id": 1
}"#;
let response = r#"{"jsonrpc":"2.0","result":{"blockHash":"0xed76641c68a1c641aee09a94b3b471f4dc0316efe5ac19cf488e2674cf8d05b5","blockNumber":"0x04510c","contractAddress":null,"cumulativeGasUsed":"0x20","gasUsed":"0x10","logs":[{"address":"0x33990122638b9132ca29c723bdf037f1a891a70c","blockHash":"0xed76641c68a1c641aee09a94b3b471f4dc0316efe5ac19cf488e2674cf8d05b5","blockNumber":"0x04510c","data":"0x","logIndex":"0x01","topics":["0xa6697e974e6a320f454390be03f74955e8978f1a6971ea6730542e37b66179bc","0x4861736852656700000000000000000000000000000000000000000000000000"],"transactionHash":"0x0000000000000000000000000000000000000000000000000000000000000000","transactionIndex":"0x00"}],"transactionHash":"0x0000000000000000000000000000000000000000000000000000000000000000","transactionIndex":"0x00"},"id":1}"#;
assert_eq!(tester.io.handle_request(request), Some(response.to_owned()));
}
#[test]
fn rpc_eth_transaction_receipt_null() {
let tester = EthTester::default();
let request = r#"{
"jsonrpc": "2.0",
"method": "eth_getTransactionReceipt",
"params": ["0xb903239f8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238"],
"id": 1
}"#;
let response = r#"{"jsonrpc":"2.0","result":null,"id":1}"#;
assert_eq!(tester.io.handle_request(request), Some(response.to_owned()));
}
#[test]
@@ -346,5 +600,26 @@ fn rpc_eth_compile_serpent() {
assert_eq!(EthTester::default().io.handle_request(request), Some(response.to_owned()));
}
#[test]
fn returns_no_work_if_cant_mine() {
let eth_tester = EthTester::default();
eth_tester.client.set_queue_size(10);
let request = r#"{"jsonrpc": "2.0", "method": "eth_getWork", "params": [], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":["","",""],"id":1}"#;
assert_eq!(eth_tester.io.handle_request(request), Some(response.to_owned()));
}
#[test]
fn returns_error_if_can_mine_and_no_closed_block() {
use ethsync::{SyncState};
let eth_tester = EthTester::default();
eth_tester.sync.status.write().unwrap().state = SyncState::Idle;
let request = r#"{"jsonrpc": "2.0", "method": "eth_getWork", "params": [], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","error":{"code":-32603,"message":"Internal error","data":null},"id":1}"#;
assert_eq!(eth_tester.io.handle_request(request), Some(response.to_owned()));
}

View File

@@ -14,11 +14,13 @@
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Test implementation of account provider.
use std::sync::RwLock;
use std::collections::HashMap;
use std::io;
use util::hash::{Address, H256};
use util::crypto::{Secret, Signature};
use util::hash::{Address, H256, FixedHash};
use util::crypto::{Secret, Signature, KeyPair};
use util::keys::store::{AccountProvider, SigningError, EncryptedHashMapError};
/// Account mock.
@@ -28,21 +30,31 @@ pub struct TestAccount {
pub unlocked: bool,
/// Account's password.
pub password: String,
/// Account's secret.
pub secret: Secret,
}
impl TestAccount {
/// Creates new test account.
pub fn new(password: &str) -> Self {
let pair = KeyPair::create().unwrap();
TestAccount {
unlocked: false,
password: password.to_owned(),
secret: pair.secret().clone()
}
}
/// Returns account address.
pub fn address(&self) -> Address {
KeyPair::from_secret(self.secret.clone()).unwrap().address()
}
}
/// Test account provider.
pub struct TestAccountProvider {
accounts: RwLock<HashMap<Address, TestAccount>>,
pub adds: RwLock<Vec<String>>,
/// Test provider accounts.
pub accounts: RwLock<HashMap<Address, TestAccount>>,
}
impl TestAccountProvider {
@@ -50,7 +62,6 @@ impl TestAccountProvider {
pub fn new(accounts: HashMap<Address, TestAccount>) -> Self {
TestAccountProvider {
accounts: RwLock::new(accounts),
adds: RwLock::new(vec![]),
}
}
}
@@ -72,14 +83,20 @@ impl AccountProvider for TestAccountProvider {
}
fn new_account(&self, pass: &str) -> Result<Address, io::Error> {
let mut adds = self.adds.write().unwrap();
let address = Address::from(adds.len() as u64 + 2);
adds.push(pass.to_owned());
let account = TestAccount::new(pass);
let address = KeyPair::from_secret(account.secret.clone()).unwrap().address();
self.accounts.write().unwrap().insert(address.clone(), account);
Ok(address)
}
fn account_secret(&self, _account: &Address) -> Result<Secret, SigningError> {
unimplemented!()
fn account_secret(&self, address: &Address) -> Result<Secret, SigningError> {
// todo: consider checking if account is unlock. some test may need alteration then.
self.accounts
.read()
.unwrap()
.get(address)
.ok_or(SigningError::NoAccount)
.map(|acc| acc.secret.clone())
}
fn sign(&self, _account: &Address, _message: &H256) -> Result<Signature, SigningError> {

View File

@@ -22,10 +22,12 @@ use v1::helpers::ExternalMinerService;
/// Test ExternalMinerService;
pub struct TestExternalMiner {
/// External miners hashrates.
pub hashrates: Arc<RwLock<HashMap<H256, U256>>>
}
impl TestExternalMiner {
/// Creates new external miner.
pub fn new(hashrates: Arc<RwLock<HashMap<H256, U256>>>) -> Self {
TestExternalMiner {
hashrates: hashrates,

View File

@@ -14,40 +14,102 @@
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use util::{Address, H256, U256, Bytes};
//! Test implementation of miner service.
use util::{Address, H256, Bytes, U256};
use util::standard::*;
use ethcore::error::Error;
use ethcore::client::BlockChainClient;
use ethcore::block::ClosedBlock;
use ethcore::transaction::SignedTransaction;
use ethminer::{MinerService, MinerStatus};
use ethminer::{MinerService, MinerStatus, AccountDetails};
pub struct TestMinerService;
/// Test miner service.
pub struct TestMinerService {
/// Imported transactions.
pub imported_transactions: Mutex<Vec<SignedTransaction>>,
/// Latest closed block.
pub latest_closed_block: Mutex<Option<ClosedBlock>>,
/// Pre-existed pending transactions
pub pending_transactions: Mutex<HashMap<H256, SignedTransaction>>,
/// Last nonces.
pub last_nonces: RwLock<HashMap<Address, U256>>,
}
impl Default for TestMinerService {
fn default() -> TestMinerService {
TestMinerService {
imported_transactions: Mutex::new(Vec::new()),
latest_closed_block: Mutex::new(None),
pending_transactions: Mutex::new(HashMap::new()),
last_nonces: RwLock::new(HashMap::new()),
}
}
}
impl MinerService for TestMinerService {
/// Returns miner's status.
fn status(&self) -> MinerStatus { unimplemented!(); }
fn status(&self) -> MinerStatus {
MinerStatus {
transactions_in_pending_queue: 0,
transactions_in_future_queue: 0,
transactions_in_pending_block: 1
}
}
/// Imports transactions to transaction queue.
fn import_transactions<T>(&self, _transactions: Vec<SignedTransaction>, _fetch_nonce: T) -> Result<(), Error> where T: Fn(&Address) -> U256 { unimplemented!(); }
fn import_transactions<T>(&self, transactions: Vec<SignedTransaction>, _fetch_account: T) -> Vec<Result<(), Error>>
where T: Fn(&Address) -> AccountDetails {
// lets assume that all txs are valid
self.imported_transactions.lock().unwrap().extend_from_slice(&transactions);
transactions
.iter()
.map(|_| Ok(()))
.collect()
}
/// Returns hashes of transactions currently in pending
fn pending_transactions_hashes(&self) -> Vec<H256> { unimplemented!(); }
fn pending_transactions_hashes(&self) -> Vec<H256> {
vec![]
}
/// Removes all transactions from the queue and restart mining operation.
fn clear_and_reset(&self, _chain: &BlockChainClient) { unimplemented!(); }
fn clear_and_reset(&self, _chain: &BlockChainClient) {
unimplemented!();
}
/// Called when blocks are imported to chain, updates transactions queue.
fn chain_new_blocks(&self, _chain: &BlockChainClient, _imported: &[H256], _invalid: &[H256], _enacted: &[H256], _retracted: &[H256]) { unimplemented!(); }
fn chain_new_blocks(&self, _chain: &BlockChainClient, _imported: &[H256], _invalid: &[H256], _enacted: &[H256], _retracted: &[H256]) {
unimplemented!();
}
/// New chain head event. Restart mining operation.
fn prepare_sealing(&self, _chain: &BlockChainClient) { unimplemented!(); }
fn update_sealing(&self, _chain: &BlockChainClient) {
unimplemented!();
}
/// Grab the `ClosedBlock` that we want to be sealed. Comes as a mutex that you have to lock.
fn sealing_block(&self, _chain: &BlockChainClient) -> &Mutex<Option<ClosedBlock>> { unimplemented!(); }
fn sealing_block(&self, _chain: &BlockChainClient) -> &Mutex<Option<ClosedBlock>> {
&self.latest_closed_block
}
fn transaction(&self, hash: &H256) -> Option<SignedTransaction> {
self.pending_transactions.lock().unwrap().get(hash).cloned()
}
fn pending_transactions(&self) -> Vec<SignedTransaction> {
self.pending_transactions.lock().unwrap().values().cloned().collect()
}
fn last_nonce(&self, address: &Address) -> Option<U256> {
self.last_nonces.read().unwrap().get(address).cloned()
}
/// Submit `seal` as a valid solution for the header of `pow_hash`.
/// Will check the seal, but not actually insert the block into the chain.
fn submit_seal(&self, _chain: &BlockChainClient, _pow_hash: H256, _seal: Vec<Bytes>) -> Result<(), Error> { unimplemented!(); }
}
fn submit_seal(&self, _chain: &BlockChainClient, _pow_hash: H256, _seal: Vec<Bytes>) -> Result<(), Error> {
unimplemented!();
}
}

View File

@@ -14,6 +14,8 @@
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Test rpc services.
mod account_provider;
mod sync_provider;
mod miner_service;

View File

@@ -14,23 +14,34 @@
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use ethsync::{SyncProvider, SyncStatus, SyncState};
//! Test implementation of SyncProvider.
use util::{U256};
use ethsync::{SyncProvider, SyncStatus, SyncState};
use std::sync::{RwLock};
/// TestSyncProvider config.
pub struct Config {
pub protocol_version: u8,
/// Protocol version.
pub network_id: U256,
/// Number of peers.
pub num_peers: usize,
}
/// Test sync provider.
pub struct TestSyncProvider {
status: SyncStatus,
/// Sync status.
pub status: RwLock<SyncStatus>,
}
impl TestSyncProvider {
/// Creates new sync provider.
pub fn new(config: Config) -> Self {
TestSyncProvider {
status: SyncStatus {
status: RwLock::new(SyncStatus {
state: SyncState::NotSynced,
protocol_version: config.protocol_version,
network_id: config.network_id,
protocol_version: 63,
start_block_number: 0,
last_imported_block_number: None,
highest_block_number: None,
@@ -39,14 +50,14 @@ impl TestSyncProvider {
num_peers: config.num_peers,
num_active_peers: 0,
mem_used: 0,
},
}),
}
}
}
impl SyncProvider for TestSyncProvider {
fn status(&self) -> SyncStatus {
self.status.clone()
self.status.read().unwrap().clone()
}
}

View File

@@ -16,8 +16,12 @@
//!TODO: load custom blockchain state and test
pub mod helpers;
#[cfg(test)]
mod eth;
#[cfg(test)]
mod net;
#[cfg(test)]
mod web3;
mod helpers;
#[cfg(test)]
mod personal;

View File

@@ -21,7 +21,7 @@ use v1::tests::helpers::{Config, TestSyncProvider};
fn sync_provider() -> Arc<TestSyncProvider> {
Arc::new(TestSyncProvider::new(Config {
protocol_version: 65,
network_id: From::from(3),
num_peers: 120,
}))
}
@@ -34,7 +34,7 @@ fn rpc_net_version() {
io.add_delegate(net);
let request = r#"{"jsonrpc": "2.0", "method": "net_version", "params": [], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":"65","id":1}"#;
let response = r#"{"jsonrpc":"2.0","result":"3","id":1}"#;
assert_eq!(io.handle_request(request), Some(response.to_owned()));
}

View File

@@ -22,8 +22,7 @@ use util::numbers::*;
use std::collections::*;
fn accounts_provider() -> Arc<TestAccountProvider> {
let mut accounts = HashMap::new();
accounts.insert(Address::from(1), TestAccount::new("test"));
let accounts = HashMap::new();
let ap = TestAccountProvider::new(accounts);
Arc::new(ap)
}
@@ -38,7 +37,11 @@ fn setup() -> (Arc<TestAccountProvider>, IoHandler) {
#[test]
fn accounts() {
let (_test_provider, io) = setup();
let (test_provider, io) = setup();
test_provider.accounts
.write()
.unwrap()
.insert(Address::from(1), TestAccount::new("test"));
let request = r#"{"jsonrpc": "2.0", "method": "personal_listAccounts", "params": [], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":["0x0000000000000000000000000000000000000001"],"id":1}"#;
@@ -49,11 +52,22 @@ fn accounts() {
#[test]
fn new_account() {
let (_test_provider, io) = setup();
let (test_provider, io) = setup();
let request = r#"{"jsonrpc": "2.0", "method": "personal_newAccount", "params": ["pass"], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":"0x0000000000000000000000000000000000000002","id":1}"#;
assert_eq!(io.handle_request(request), Some(response.to_owned()));
let res = io.handle_request(request);
let accounts = test_provider.accounts.read().unwrap();
assert_eq!(accounts.len(), 1);
let address = accounts
.keys()
.nth(0)
.cloned()
.unwrap();
let response = r#"{"jsonrpc":"2.0","result":""#.to_owned() + format!("0x{:?}", address).as_ref() + r#"","id":1}"#;
assert_eq!(res, Some(response));
}

View File

@@ -31,3 +31,27 @@ fn rpc_web3_version() {
assert_eq!(io.handle_request(request), Some(response));
}
#[test]
fn rpc_web3_sha3() {
let web3 = Web3Client::new().to_delegate();
let io = IoHandler::new();
io.add_delegate(web3);
let request = r#"{"jsonrpc": "2.0", "method": "web3_sha3", "params": ["0x00"], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":"0xbc36789e7a1e281436464229828f817d6612f7b477d66591ff96a9e064bcc98a","id":1}"#;
assert_eq!(io.handle_request(request), Some(response.to_owned()));
}
#[test]
fn rpc_web3_sha3_wiki() {
let web3 = Web3Client::new().to_delegate();
let io = IoHandler::new();
io.add_delegate(web3);
let request = r#"{"jsonrpc": "2.0", "method": "web3_sha3", "params": ["0x68656c6c6f20776f726c64"], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":"0x47173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad","id":1}"#;
assert_eq!(io.handle_request(request), Some(response.to_owned()));
}

View File

@@ -190,7 +190,7 @@ pub trait EthFilter: Sized + Send + Sync + 'static {
/// Returns filter changes since last poll.
fn filter_changes(&self, _: Params) -> Result<Value, Error> { rpc_unimplemented!() }
/// Returns filter logs.
/// Returns all logs matching given filter (in a range 'from' - 'to').
fn filter_logs(&self, _: Params) -> Result<Value, Error> { rpc_unimplemented!() }
/// Uninstalls filter.

View File

@@ -23,10 +23,14 @@ pub trait Web3: Sized + Send + Sync + 'static {
/// Returns current client version.
fn client_version(&self, _: Params) -> Result<Value, Error> { rpc_unimplemented!() }
/// Returns sha3 of the given data
fn sha3(&self, _: Params) -> Result<Value, Error> { rpc_unimplemented!() }
/// Should be used to convert object to io delegate.
fn to_delegate(self) -> IoDelegate<Self> {
let mut delegate = IoDelegate::new(Arc::new(self));
delegate.add_method("web3_clientVersion", Web3::client_version);
delegate.add_method("web3_sha3", Web3::sha3);
delegate
}
}

View File

@@ -63,7 +63,8 @@ pub struct Block {
pub difficulty: U256,
#[serde(rename="totalDifficulty")]
pub total_difficulty: U256,
pub uncles: Vec<U256>,
pub nonce: H64,
pub uncles: Vec<H256>,
pub transactions: BlockTransactions
}
@@ -78,7 +79,7 @@ mod tests {
fn test_serialize_block_transactions() {
let t = BlockTransactions::Full(vec![Transaction::default()]);
let serialized = serde_json::to_string(&t).unwrap();
assert_eq!(serialized, r#"[{"hash":"0x0000000000000000000000000000000000000000000000000000000000000000","nonce":"0x00","blockHash":null,"blockNumber":null,"transactionIndex":null,"from":"0x0000000000000000000000000000000000000000","to":null,"value":"0x00","gasPrice":"0x00","gas":"0x00","input":"0x00"}]"#);
assert_eq!(serialized, r#"[{"hash":"0x0000000000000000000000000000000000000000000000000000000000000000","nonce":"0x00","blockHash":null,"blockNumber":null,"transactionIndex":null,"from":"0x0000000000000000000000000000000000000000","to":null,"value":"0x00","gasPrice":"0x00","gas":"0x00","input":"0x"}]"#);
let t = BlockTransactions::Hashes(vec![H256::default()]);
let serialized = serde_json::to_string(&t).unwrap();
@@ -104,11 +105,12 @@ mod tests {
timestamp: U256::default(),
difficulty: U256::default(),
total_difficulty: U256::default(),
nonce: H64::default(),
uncles: vec![],
transactions: BlockTransactions::Hashes(vec![])
};
let serialized = serde_json::to_string(&block).unwrap();
assert_eq!(serialized, r#"{"hash":"0x0000000000000000000000000000000000000000000000000000000000000000","parentHash":"0x0000000000000000000000000000000000000000000000000000000000000000","sha3Uncles":"0x0000000000000000000000000000000000000000000000000000000000000000","author":"0x0000000000000000000000000000000000000000","miner":"0x0000000000000000000000000000000000000000","stateRoot":"0x0000000000000000000000000000000000000000000000000000000000000000","transactionsRoot":"0x0000000000000000000000000000000000000000000000000000000000000000","receiptsRoot":"0x0000000000000000000000000000000000000000000000000000000000000000","number":"0x00","gasUsed":"0x00","gasLimit":"0x00","extraData":"0x00","logsBloom":"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","timestamp":"0x00","difficulty":"0x00","totalDifficulty":"0x00","uncles":[],"transactions":[]}"#);
assert_eq!(serialized, r#"{"hash":"0x0000000000000000000000000000000000000000000000000000000000000000","parentHash":"0x0000000000000000000000000000000000000000000000000000000000000000","sha3Uncles":"0x0000000000000000000000000000000000000000000000000000000000000000","author":"0x0000000000000000000000000000000000000000","miner":"0x0000000000000000000000000000000000000000","stateRoot":"0x0000000000000000000000000000000000000000000000000000000000000000","transactionsRoot":"0x0000000000000000000000000000000000000000000000000000000000000000","receiptsRoot":"0x0000000000000000000000000000000000000000000000000000000000000000","number":"0x00","gasUsed":"0x00","gasLimit":"0x00","extraData":"0x","logsBloom":"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","timestamp":"0x00","difficulty":"0x00","totalDifficulty":"0x00","nonce":"0x0000000000000000","uncles":[],"transactions":[]}"#);
}
}

View File

@@ -20,8 +20,8 @@ use serde::de::Visitor;
use util::common::FromHex;
/// Wrapper structure around vector of bytes.
#[derive(Debug, PartialEq)]
pub struct Bytes(Vec<u8>);
#[derive(Debug, PartialEq, Default)]
pub struct Bytes(pub Vec<u8>);
impl Bytes {
/// Simple constructor.
@@ -31,13 +31,6 @@ impl Bytes {
pub fn to_vec(self) -> Vec<u8> { let Bytes(x) = self; x }
}
impl Default for Bytes {
fn default() -> Self {
// default serialized value is 0x00
Bytes(vec![0])
}
}
impl Serialize for Bytes {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
where S: Serializer {

View File

@@ -0,0 +1,105 @@
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use util::hash::Address;
use util::numbers::U256;
use v1::types::Bytes;
#[derive(Debug, Default, PartialEq, Deserialize)]
pub struct CallRequest {
pub from: Option<Address>,
pub to: Option<Address>,
#[serde(rename="gasPrice")]
pub gas_price: Option<U256>,
pub gas: Option<U256>,
pub value: Option<U256>,
pub data: Option<Bytes>,
pub nonce: Option<U256>,
}
#[cfg(test)]
mod tests {
use std::str::FromStr;
use rustc_serialize::hex::FromHex;
use serde_json;
use util::numbers::{U256};
use util::hash::Address;
use v1::types::Bytes;
use super::*;
#[test]
fn transaction_request_deserialize() {
let s = r#"{
"from":"0x0000000000000000000000000000000000000001",
"to":"0x0000000000000000000000000000000000000002",
"gasPrice":"0x1",
"gas":"0x2",
"value":"0x3",
"data":"0x123456",
"nonce":"0x4"
}"#;
let deserialized: CallRequest = serde_json::from_str(s).unwrap();
assert_eq!(deserialized, CallRequest {
from: Some(Address::from(1)),
to: Some(Address::from(2)),
gas_price: Some(U256::from(1)),
gas: Some(U256::from(2)),
value: Some(U256::from(3)),
data: Some(Bytes::new(vec![0x12, 0x34, 0x56])),
nonce: Some(U256::from(4)),
});
}
#[test]
fn transaction_request_deserialize2() {
let s = r#"{
"from": "0xb60e8dd61c5d32be8058bb8eb970870f07233155",
"to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567",
"gas": "0x76c0",
"gasPrice": "0x9184e72a000",
"value": "0x9184e72a",
"data": "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675"
}"#;
let deserialized: CallRequest = serde_json::from_str(s).unwrap();
assert_eq!(deserialized, CallRequest {
from: Some(Address::from_str("b60e8dd61c5d32be8058bb8eb970870f07233155").unwrap()),
to: Some(Address::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap()),
gas_price: Some(U256::from_str("9184e72a000").unwrap()),
gas: Some(U256::from_str("76c0").unwrap()),
value: Some(U256::from_str("9184e72a").unwrap()),
data: Some(Bytes::new("d46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675".from_hex().unwrap())),
nonce: None
});
}
#[test]
fn transaction_request_deserialize_empty() {
let s = r#"{"from":"0x0000000000000000000000000000000000000001"}"#;
let deserialized: CallRequest = serde_json::from_str(s).unwrap();
assert_eq!(deserialized, CallRequest {
from: Some(Address::from(1)),
to: None,
gas_price: None,
gas: None,
value: None,
data: None,
nonce: None,
});
}
}

View File

@@ -20,19 +20,19 @@ use v1::types::Bytes;
#[derive(Debug, Serialize)]
pub struct Log {
address: Address,
topics: Vec<H256>,
data: Bytes,
pub address: Address,
pub topics: Vec<H256>,
pub data: Bytes,
#[serde(rename="blockHash")]
block_hash: H256,
pub block_hash: H256,
#[serde(rename="blockNumber")]
block_number: U256,
pub block_number: U256,
#[serde(rename="transactionHash")]
transaction_hash: H256,
pub transaction_hash: H256,
#[serde(rename="transactionIndex")]
transaction_index: U256,
pub transaction_index: U256,
#[serde(rename="logIndex")]
log_index: U256,
pub log_index: U256,
}
impl From<LocalizedLogEntry> for Log {

View File

@@ -24,6 +24,8 @@ mod optionals;
mod sync;
mod transaction;
mod transaction_request;
mod call_request;
mod receipt;
pub use self::block::{Block, BlockTransactions};
pub use self::block_number::BlockNumber;
@@ -35,4 +37,6 @@ pub use self::optionals::OptionalValue;
pub use self::sync::{SyncStatus, SyncInfo};
pub use self::transaction::Transaction;
pub use self::transaction_request::TransactionRequest;
pub use self::call_request::CallRequest;
pub use self::receipt::Receipt;

View File

@@ -0,0 +1,94 @@
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use util::numbers::U256;
use util::hash::{Address, H256};
use v1::types::Log;
use ethcore::receipt::LocalizedReceipt;
#[derive(Debug, Serialize)]
pub struct Receipt {
#[serde(rename="transactionHash")]
pub transaction_hash: H256,
#[serde(rename="transactionIndex")]
pub transaction_index: U256,
#[serde(rename="blockHash")]
pub block_hash: H256,
#[serde(rename="blockNumber")]
pub block_number: U256,
#[serde(rename="cumulativeGasUsed")]
pub cumulative_gas_used: U256,
#[serde(rename="gasUsed")]
pub gas_used: U256,
#[serde(rename="contractAddress")]
pub contract_address: Option<Address>,
pub logs: Vec<Log>,
}
impl From<LocalizedReceipt> for Receipt {
fn from(r: LocalizedReceipt) -> Self {
Receipt {
transaction_hash: r.transaction_hash,
transaction_index: U256::from(r.transaction_index),
block_hash: r.block_hash,
block_number: U256::from(r.block_number),
cumulative_gas_used: r.cumulative_gas_used,
gas_used: r.gas_used,
contract_address: r.contract_address,
logs: r.logs.into_iter().map(From::from).collect(),
}
}
}
#[cfg(test)]
mod tests {
use serde_json;
use std::str::FromStr;
use util::numbers::*;
use v1::types::{Bytes, Log, Receipt};
#[test]
fn receipt_serialization() {
let s = r#"{"transactionHash":"0x0000000000000000000000000000000000000000000000000000000000000000","transactionIndex":"0x00","blockHash":"0xed76641c68a1c641aee09a94b3b471f4dc0316efe5ac19cf488e2674cf8d05b5","blockNumber":"0x04510c","cumulativeGasUsed":"0x20","gasUsed":"0x10","contractAddress":null,"logs":[{"address":"0x33990122638b9132ca29c723bdf037f1a891a70c","topics":["0xa6697e974e6a320f454390be03f74955e8978f1a6971ea6730542e37b66179bc","0x4861736852656700000000000000000000000000000000000000000000000000"],"data":"0x","blockHash":"0xed76641c68a1c641aee09a94b3b471f4dc0316efe5ac19cf488e2674cf8d05b5","blockNumber":"0x04510c","transactionHash":"0x0000000000000000000000000000000000000000000000000000000000000000","transactionIndex":"0x00","logIndex":"0x01"}]}"#;
let receipt = Receipt {
transaction_hash: H256::zero(),
transaction_index: U256::zero(),
block_hash: H256::from_str("ed76641c68a1c641aee09a94b3b471f4dc0316efe5ac19cf488e2674cf8d05b5").unwrap(),
block_number: U256::from(0x4510c),
cumulative_gas_used: U256::from(0x20),
gas_used: U256::from(0x10),
contract_address: None,
logs: vec![Log {
address: Address::from_str("33990122638b9132ca29c723bdf037f1a891a70c").unwrap(),
topics: vec![
H256::from_str("a6697e974e6a320f454390be03f74955e8978f1a6971ea6730542e37b66179bc").unwrap(),
H256::from_str("4861736852656700000000000000000000000000000000000000000000000000").unwrap()
],
data: Bytes::new(vec![]),
block_hash: H256::from_str("ed76641c68a1c641aee09a94b3b471f4dc0316efe5ac19cf488e2674cf8d05b5").unwrap(),
block_number: U256::from(0x4510c),
transaction_hash: H256::new(),
transaction_index: U256::zero(),
log_index: U256::one()
}]
};
let serialized = serde_json::to_string(&receipt).unwrap();
assert_eq!(serialized, s);
}
}

View File

@@ -15,7 +15,7 @@
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use util::numbers::*;
use ethcore::transaction::{LocalizedTransaction, Action};
use ethcore::transaction::{LocalizedTransaction, Action, SignedTransaction};
use v1::types::{Bytes, OptionalValue};
#[derive(Debug, Default, Serialize)]
@@ -58,6 +58,27 @@ impl From<LocalizedTransaction> for Transaction {
}
}
impl From<SignedTransaction> for Transaction {
fn from(t: SignedTransaction) -> Transaction {
Transaction {
hash: t.hash(),
nonce: t.nonce,
block_hash: OptionalValue::Null,
block_number: OptionalValue::Null,
transaction_index: OptionalValue::Null,
from: t.sender().unwrap(),
to: match t.action {
Action::Create => OptionalValue::Null,
Action::Call(ref address) => OptionalValue::Value(address.clone())
},
value: t.value,
gas_price: t.gas_price,
gas: t.gas,
input: Bytes::new(t.data.clone())
}
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -67,7 +88,7 @@ mod tests {
fn test_transaction_serialize() {
let t = Transaction::default();
let serialized = serde_json::to_string(&t).unwrap();
assert_eq!(serialized, r#"{"hash":"0x0000000000000000000000000000000000000000000000000000000000000000","nonce":"0x00","blockHash":null,"blockNumber":null,"transactionIndex":null,"from":"0x0000000000000000000000000000000000000000","to":null,"value":"0x00","gasPrice":"0x00","gas":"0x00","input":"0x00"}"#);
assert_eq!(serialized, r#"{"hash":"0x0000000000000000000000000000000000000000000000000000000000000000","nonce":"0x00","blockHash":null,"blockNumber":null,"transactionIndex":null,"from":"0x0000000000000000000000000000000000000000","to":null,"value":"0x00","gasPrice":"0x00","gas":"0x00","input":"0x"}"#);
}
}

View File

@@ -15,8 +15,7 @@
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use util::hash::Address;
use util::numbers::{Uint, U256};
use ethcore::transaction::{Action, Transaction};
use util::numbers::U256;
use v1::types::Bytes;
#[derive(Debug, Default, PartialEq, Deserialize)]
@@ -31,72 +30,16 @@ pub struct TransactionRequest {
pub nonce: Option<U256>,
}
impl Into<Transaction> for TransactionRequest {
fn into(self) -> Transaction {
Transaction {
nonce: self.nonce.unwrap_or_else(U256::zero),
action: self.to.map_or(Action::Create, Action::Call),
gas: self.gas.unwrap_or_else(U256::zero),
gas_price: self.gas_price.unwrap_or_else(U256::zero),
value: self.value.unwrap_or_else(U256::zero),
data: self.data.map_or_else(Vec::new, |d| d.to_vec()),
}
}
}
#[cfg(test)]
mod tests {
use std::str::FromStr;
use rustc_serialize::hex::FromHex;
use serde_json;
use util::numbers::{Uint, U256};
use util::numbers::{U256};
use util::hash::Address;
use ethcore::transaction::{Transaction, Action};
use v1::types::Bytes;
use super::*;
#[test]
fn transaction_request_into_transaction() {
let tr = TransactionRequest {
from: Address::default(),
to: Some(Address::from(10)),
gas_price: Some(U256::from(20)),
gas: Some(U256::from(10_000)),
value: Some(U256::from(1)),
data: Some(Bytes::new(vec![10, 20])),
nonce: Some(U256::from(12)),
};
assert_eq!(Transaction {
nonce: U256::from(12),
action: Action::Call(Address::from(10)),
gas: U256::from(10_000),
gas_price: U256::from(20),
value: U256::from(1),
data: vec![10, 20],
}, tr.into());
}
#[test]
fn empty_transaction_request_into_transaction() {
let tr = TransactionRequest {
from: Address::default(),
to: None,
gas_price: None,
gas: None,
value: None,
data: None,
nonce: None,
};
assert_eq!(Transaction {
nonce: U256::zero(),
action: Action::Create,
gas: U256::zero(),
gas_price: U256::zero(),
value: U256::zero(),
data: vec![],
}, tr.into());
}
#[test]
fn transaction_request_deserialize() {
let s = r#"{
@@ -121,6 +64,29 @@ mod tests {
});
}
#[test]
fn transaction_request_deserialize2() {
let s = r#"{
"from": "0xb60e8dd61c5d32be8058bb8eb970870f07233155",
"to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567",
"gas": "0x76c0",
"gasPrice": "0x9184e72a000",
"value": "0x9184e72a",
"data": "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675"
}"#;
let deserialized: TransactionRequest = serde_json::from_str(s).unwrap();
assert_eq!(deserialized, TransactionRequest {
from: Address::from_str("b60e8dd61c5d32be8058bb8eb970870f07233155").unwrap(),
to: Some(Address::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap()),
gas_price: Some(U256::from_str("9184e72a000").unwrap()),
gas: Some(U256::from_str("76c0").unwrap()),
value: Some(U256::from_str("9184e72a").unwrap()),
data: Some(Bytes::new("d46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675".from_hex().unwrap())),
nonce: None
});
}
#[test]
fn transaction_request_deserialize_empty() {
let s = r#"{"from":"0x0000000000000000000000000000000000000001"}"#;
@@ -136,4 +102,27 @@ mod tests {
nonce: None,
});
}
#[test]
fn transaction_request_deserialize_test() {
let s = r#"{
"from":"0xb5f7502a2807cb23615c7456055e1d65b2508625",
"to":"0x895d32f2db7d01ebb50053f9e48aacf26584fe40",
"data":"0x8595bab1",
"gas":"0x2fd618",
"gasPrice":"0x0ba43b7400"
}"#;
let deserialized: TransactionRequest = serde_json::from_str(s).unwrap();
assert_eq!(deserialized, TransactionRequest {
from: Address::from_str("b5f7502a2807cb23615c7456055e1d65b2508625").unwrap(),
to: Some(Address::from_str("895d32f2db7d01ebb50053f9e48aacf26584fe40").unwrap()),
gas_price: Some(U256::from_str("0ba43b7400").unwrap()),
gas: Some(U256::from_str("2fd618").unwrap()),
value: None,
data: Some(Bytes::new(vec![0x85, 0x95, 0xba, 0xb1])),
nonce: None,
});
}
}

View File

@@ -1,7 +1,7 @@
[package]
description = "Ethcore blockchain sync"
name = "ethsync"
version = "1.1.0"
version = "1.0.2"
license = "GPL-3.0"
authors = ["Ethcore <admin@ethcore.io"]
@@ -10,7 +10,7 @@ authors = ["Ethcore <admin@ethcore.io"]
[dependencies]
ethcore-util = { path = "../util" }
ethcore = { path = "../ethcore" }
clippy = { version = "0.0.50", optional = true }
clippy = { version = "0.0.54", optional = true }
ethminer = { path = "../miner" }
log = "0.3"
env_logger = "0.3"

View File

@@ -38,7 +38,7 @@ use range_collection::{RangeCollection, ToUsize, FromUsize};
use ethcore::error::*;
use ethcore::transaction::SignedTransaction;
use ethcore::block::Block;
use ethminer::{Miner, MinerService};
use ethminer::{Miner, MinerService, AccountDetails};
use io::SyncIo;
use time;
use super::SyncConfig;
@@ -125,6 +125,8 @@ pub struct SyncStatus {
pub state: SyncState,
/// Syncing protocol version. That's the maximum protocol version we connect to.
pub protocol_version: u8,
/// The underlying p2p network version.
pub network_id: U256,
/// BlockChain height for the moment the sync started.
pub start_block_number: BlockNumber,
/// Last fully downloaded and imported block number (if any).
@@ -249,6 +251,7 @@ impl ChainSync {
SyncStatus {
state: self.state.clone(),
protocol_version: 63,
network_id: self.network_id,
start_block_number: self.starting_block,
last_imported_block_number: self.last_imported_block,
highest_block_number: self.highest_block,
@@ -274,7 +277,6 @@ impl ChainSync {
self.peers.clear();
}
#[cfg_attr(feature="dev", allow(for_kv_map))] // Because it's not possible to get `values_mut()`
/// Rest sync. Clear all downloaded data but keep the queue
fn reset(&mut self) {
@@ -301,6 +303,13 @@ impl ChainSync {
self.state = SyncState::NotSynced;
}
/// Restart sync after bad block has been detected. May end up re-downloading up to QUEUE_SIZE blocks
pub fn restart_on_bad_block(&mut self, io: &mut SyncIo) {
self.restart(io);
// Do not assume that the block queue/chain still has our last_imported_block
self.last_imported_block = None;
self.last_imported_hash = None;
}
/// Called by peer to report status
fn on_peer_status(&mut self, io: &mut SyncIo, peer_id: PeerId, r: &UntrustedRlp) -> Result<(), PacketDecodeError> {
let peer = PeerInfo {
@@ -378,7 +387,10 @@ impl ChainSync {
self.have_common_block = true;
trace!(target: "sync", "Found common header {} ({})", number, hash);
} else {
trace!(target: "sync", "Header already in chain {} ({})", number, hash);
trace!(target: "sync", "Header already in chain {} ({}), restarting", number, hash);
self.restart(io);
self.continue_sync(io);
return Ok(());
}
},
_ => {
@@ -402,6 +414,12 @@ impl ChainSync {
debug!(target: "sync", "Mismatched block header {}", number + 1);
self.remove_downloaded_blocks(number + 1);
}
if self.have_common_block && number < self.current_base_block() + 1 {
// unkown header
debug!(target: "sync", "Old block header {:?} ({}) is unknown, restarting sync", hash, number);
self.restart(io);
return Ok(());
}
}
let hdr = Header {
data: try!(r.at(i)).as_raw().to_vec(),
@@ -447,6 +465,12 @@ impl ChainSync {
trace!(target: "sync", "Ignored block bodies while waiting");
return Ok(());
}
if item_count == 0 {
trace!(target: "sync", "No bodies returned, restarting");
self.restart(io);
self.continue_sync(io);
return Ok(());
}
for i in 0..item_count {
let body = try!(r.at(i));
let tx = try!(body.at(0));
@@ -832,7 +856,7 @@ impl ChainSync {
}
if restart {
self.restart(io);
self.restart_on_bad_block(io);
return;
}
@@ -929,8 +953,14 @@ impl ChainSync {
sync.disable_peer(peer_id);
}
}
/// Called when peer sends us new transactions
fn on_peer_transactions(&mut self, io: &mut SyncIo, peer_id: PeerId, r: &UntrustedRlp) -> Result<(), PacketDecodeError> {
// accepting transactions once only fully synced
if !io.is_chain_queue_empty() {
return Ok(());
}
let item_count = r.item_count();
trace!(target: "sync", "{} -> Transactions ({} entries)", peer_id, item_count);
@@ -940,8 +970,11 @@ impl ChainSync {
transactions.push(tx);
}
let chain = io.chain();
let fetch_nonce = |a: &Address| chain.nonce(a);
let _ = self.miner.import_transactions(transactions, fetch_nonce);
let fetch_account = |a: &Address| AccountDetails {
nonce: chain.nonce(a),
balance: chain.balance(a),
};
let _ = self.miner.import_transactions(transactions, fetch_account);
Ok(())
}
@@ -1254,7 +1287,48 @@ impl ChainSync {
sent
}
/// propagates new transactions to all peers
fn propagate_new_transactions(&mut self, io: &mut SyncIo) -> usize {
// Early out of nobody to send to.
if self.peers.len() == 0 {
return 0;
}
let mut transactions = self.miner.pending_transactions();
if transactions.is_empty() {
return 0;
}
let mut packet = RlpStream::new_list(transactions.len());
let tx_count = transactions.len();
for tx in transactions.drain(..) {
packet.append(&tx);
}
let rlp = packet.out();
let lucky_peers = {
// sqrt(x)/x scaled to max u32
let fraction = (self.peers.len() as f64).powf(-0.5).mul(u32::max_value() as f64).round() as u32;
let small = self.peers.len() < MIN_PEERS_PROPAGATION;
let lucky_peers = self.peers.iter()
.filter_map(|(&p, _)| if small || ::rand::random::<u32>() < fraction { Some(p.clone()) } else { None })
.collect::<Vec<_>>();
// taking at max of MAX_PEERS_PROPAGATION
lucky_peers.iter().map(|&id| id.clone()).take(min(lucky_peers.len(), MAX_PEERS_PROPAGATION)).collect::<Vec<PeerId>>()
};
let sent = lucky_peers.len();
for peer_id in lucky_peers {
self.send_packet(io, peer_id, TRANSACTIONS_PACKET, rlp.clone());
}
trace!(target: "sync", "Sent {} transactions to {} peers.", tx_count, sent);
sent
}
fn propagate_latest_blocks(&mut self, io: &mut SyncIo) {
self.propagate_new_transactions(io);
let chain_info = io.chain().chain_info();
if (((chain_info.best_block_number as i64) - (self.last_sent_block_number as i64)).abs() as BlockNumber) < MAX_PEER_LAG_PROPAGATION {
let blocks = self.propagate_blocks(&chain_info, io);
@@ -1273,15 +1347,21 @@ impl ChainSync {
/// called when block is imported to chain, updates transactions queue and propagates the blocks
pub fn chain_new_blocks(&mut self, io: &mut SyncIo, imported: &[H256], invalid: &[H256], enacted: &[H256], retracted: &[H256]) {
// Notify miner
self.miner.chain_new_blocks(io.chain(), imported, invalid, enacted, retracted);
// Propagate latests blocks
self.propagate_latest_blocks(io);
if io.is_chain_queue_empty() {
// Notify miner
self.miner.chain_new_blocks(io.chain(), imported, invalid, enacted, retracted);
// Propagate latests blocks
self.propagate_latest_blocks(io);
}
if !invalid.is_empty() {
trace!(target: "sync", "Bad blocks in the queue, restarting");
self.restart_on_bad_block(io);
}
// TODO [todr] propagate transactions?
}
pub fn chain_new_head(&mut self, io: &mut SyncIo) {
self.miner.prepare_sealing(io.chain());
self.miner.update_sealing(io.chain());
}
}
@@ -1292,6 +1372,7 @@ mod tests {
use ::SyncConfig;
use util::*;
use super::{PeerInfo, PeerAsking};
use ethcore::views::BlockView;
use ethcore::header::*;
use ethcore::client::*;
use ethminer::{Miner, MinerService};
@@ -1622,19 +1703,53 @@ mod tests {
let good_blocks = vec![client.block_hash_delta_minus(2)];
let retracted_blocks = vec![client.block_hash_delta_minus(1)];
// Add some balance to clients
for h in vec![good_blocks[0], retracted_blocks[0]] {
let block = client.block(BlockId::Hash(h)).unwrap();
let view = BlockView::new(&block);
client.set_balance(view.transactions()[0].sender().unwrap(), U256::from(1_000_000_000));
}
let mut queue = VecDeque::new();
let mut io = TestIo::new(&mut client, &mut queue, None);
// when
sync.chain_new_blocks(&mut io, &[], &[], &[], &good_blocks);
assert_eq!(sync.miner.status().transaction_queue_future, 0);
assert_eq!(sync.miner.status().transaction_queue_pending, 1);
assert_eq!(sync.miner.status().transactions_in_future_queue, 0);
assert_eq!(sync.miner.status().transactions_in_pending_queue, 1);
sync.chain_new_blocks(&mut io, &good_blocks, &[], &[], &retracted_blocks);
// then
let status = sync.miner.status();
assert_eq!(status.transaction_queue_pending, 1);
assert_eq!(status.transaction_queue_future, 0);
assert_eq!(status.transactions_in_pending_queue, 1);
assert_eq!(status.transactions_in_future_queue, 0);
}
#[test]
fn should_not_add_transactions_to_queue_if_not_synced() {
// given
let mut client = TestBlockChainClient::new();
client.add_blocks(98, EachBlockWith::Uncle);
client.add_blocks(1, EachBlockWith::UncleAndTransaction);
client.add_blocks(1, EachBlockWith::Transaction);
let mut sync = dummy_sync_with_peer(client.block_hash_delta_minus(5));
let good_blocks = vec![client.block_hash_delta_minus(2)];
let retracted_blocks = vec![client.block_hash_delta_minus(1)];
let mut queue = VecDeque::new();
let mut io = TestIo::new(&mut client, &mut queue, None);
// when
sync.chain_new_blocks(&mut io, &[], &[], &[], &good_blocks);
assert_eq!(sync.miner.status().transactions_in_future_queue, 0);
assert_eq!(sync.miner.status().transactions_in_pending_queue, 0);
sync.chain_new_blocks(&mut io, &good_blocks, &[], &[], &retracted_blocks);
// then
let status = sync.miner.status();
assert_eq!(status.transactions_in_pending_queue, 0);
assert_eq!(status.transactions_in_future_queue, 0);
}
#[test]

Some files were not shown because too many files have changed in this diff Show More