Browse Source

Merge branch 'develop' into mk_jsonrpc_upgrade

Conflicts:
	libweb3jsonrpc/abstractwebthreestubserver.h
	libweb3jsonrpc/spec.json
	test/webthreestubclient.h
cl-refactor
Marek Kotewicz 10 years ago
parent
commit
93089bbbf0
  1. 20
      alethzero/MainWin.cpp
  2. 2
      alethzero/MainWin.h
  3. 4
      libethereum/BlockChain.h
  4. 78
      libethereum/Client.cpp
  5. 14
      libethereum/Client.h
  6. 18
      libethereum/Interface.h
  7. 1
      libethereum/MessageFilter.h
  8. 10
      libethereum/State.cpp
  9. 2
      libethereum/State.h
  10. 1068
      libjsqrc/ethereum.js
  11. 3
      libjsqrc/js.qrc
  12. 467
      libjsqrc/main.js
  13. 49
      libjsqrc/qt.js
  14. 2
      libjsqrc/setup.js
  15. 3
      libqethereum/QEthereum.h
  16. 2
      libweb3jsonrpc/CMakeLists.txt
  17. 236
      libweb3jsonrpc/WebThreeStubServer.cpp
  18. 8
      libweb3jsonrpc/WebThreeStubServer.h
  19. 41
      libweb3jsonrpc/abstractwebthreestubserver.h
  20. 9
      libweb3jsonrpc/spec.json
  21. 2
      stdserv.js
  22. 66
      test/jsonrpc.cpp
  23. 48
      test/webthreestubclient.h
  24. 17
      third/MainWin.cpp
  25. 4
      third/MainWin.h

20
alethzero/MainWin.cpp

@ -241,7 +241,7 @@ void Main::onKeysChanged()
installBalancesWatch();
}
unsigned Main::installWatch(dev::eth::MessageFilter const& _tf, std::function<void()> const& _f)
unsigned Main::installWatch(dev::eth::LogFilter const& _tf, std::function<void()> const& _f)
{
auto ret = ethereum()->installWatch(_tf);
m_handlers[ret] = _f;
@ -263,8 +263,8 @@ void Main::uninstallWatch(unsigned _w)
void Main::installWatches()
{
installWatch(dev::eth::MessageFilter().altered(c_config, 0), [=](){ installNameRegWatch(); });
installWatch(dev::eth::MessageFilter().altered(c_config, 1), [=](){ installCurrenciesWatch(); });
installWatch(dev::eth::LogFilter().address(c_config), [=]() { installNameRegWatch(); });
installWatch(dev::eth::LogFilter().address(c_config), [=]() { installCurrenciesWatch(); });
installWatch(dev::eth::PendingChangedFilter, [=](){ onNewPending(); });
installWatch(dev::eth::ChainChangedFilter, [=](){ onNewBlock(); });
}
@ -272,29 +272,26 @@ void Main::installWatches()
void Main::installNameRegWatch()
{
uninstallWatch(m_nameRegFilter);
m_nameRegFilter = installWatch(dev::eth::MessageFilter().altered((u160)ethereum()->stateAt(c_config, 0)), [=](){ onNameRegChange(); });
m_nameRegFilter = installWatch(dev::eth::LogFilter().address((u160)ethereum()->stateAt(c_config, 0)), [=](){ onNameRegChange(); });
}
void Main::installCurrenciesWatch()
{
uninstallWatch(m_currenciesFilter);
m_currenciesFilter = installWatch(dev::eth::MessageFilter().altered((u160)ethereum()->stateAt(c_config, 1)), [=](){ onCurrenciesChange(); });
m_currenciesFilter = installWatch(dev::eth::LogFilter().address((u160)ethereum()->stateAt(c_config, 1)), [=](){ onCurrenciesChange(); });
}
void Main::installBalancesWatch()
{
dev::eth::MessageFilter tf;
dev::eth::LogFilter tf;
vector<Address> altCoins;
Address coinsAddr = right160(ethereum()->stateAt(c_config, 1));
for (unsigned i = 0; i < ethereum()->stateAt(coinsAddr, 0); ++i)
altCoins.push_back(right160(ethereum()->stateAt(coinsAddr, i + 1)));
for (auto i: m_myKeys)
{
tf.altered(i.address());
for (auto c: altCoins)
tf.altered(c, (u160)i.address());
}
tf.address(c).topic(h256(i.address(), h256::AlignRight));
uninstallWatch(m_balancesFilter);
m_balancesFilter = installWatch(tf, [=](){ onBalancesChange(); });
@ -1292,7 +1289,7 @@ void Main::on_blocks_currentItemChanged()
Transaction tx(block[1][txi].data());
auto ss = tx.safeSender();
h256 th = sha3(rlpList(ss, tx.nonce()));
auto receipt = ethereum()->blockChain().receipts(h).receipts[txi];
TransactionReceipt receipt = ethereum()->blockChain().receipts(h).receipts[txi];
s << "<h3>" << th << "</h3>";
s << "<h4>" << h << "[<b>" << txi << "</b>]</h4>";
s << "<br/>From: <b>" << pretty(ss).toHtmlEscaped().toStdString() << "</b> " << ss;
@ -1308,6 +1305,7 @@ void Main::on_blocks_currentItemChanged()
s << "<br/>R: <b>" << hex << nouppercase << tx.signature().r << "</b>";
s << "<br/>S: <b>" << hex << nouppercase << tx.signature().s << "</b>";
s << "<br/>Msg: <b>" << tx.sha3(eth::WithoutSignature) << "</b>";
s << "<div>Log Bloom: " << receipt.bloom() << "</div>";
s << "<div>Hex: <span style=\"font-family: Monospace,Lucida Console,Courier,Courier New,sans-serif; font-size: small\">" << toHex(block[1][txi].data()) << "</span></div>";
auto r = receipt.rlp();
s << "<div>Receipt: " << toString(RLP(r)) << "</div>";

2
alethzero/MainWin.h

@ -189,7 +189,7 @@ private:
dev::u256 value() const;
dev::u256 gasPrice() const;
unsigned installWatch(dev::eth::MessageFilter const& _tf, std::function<void()> const& _f);
unsigned installWatch(dev::eth::LogFilter const& _tf, std::function<void()> const& _f);
unsigned installWatch(dev::h256 _tf, std::function<void()> const& _f);
void uninstallWatch(unsigned _w);

4
libethereum/BlockChain.h

@ -93,6 +93,10 @@ public:
/// Returns true if the given block is known (though not necessarily a part of the canon chain).
bool isKnown(h256 _hash) const;
/// Get the familial details concerning a block (or the most recent mined if none given). Thread-safe.
BlockInfo info(h256 _hash) const { return BlockInfo(block(_hash)); }
BlockInfo info() const { return BlockInfo(block()); }
/// Get the familial details concerning a block (or the most recent mined if none given). Thread-safe.
BlockDetails details(h256 _hash) const { return queryExtras<BlockDetails, 0>(_hash, m_details, x_details, NullBlockDetails); }
BlockDetails details() const { return details(currentHash()); }

78
libethereum/Client.cpp

@ -159,7 +159,7 @@ void Client::clearPending()
if (!m_postMine.pending().size())
return;
for (unsigned i = 0; i < m_postMine.pending().size(); ++i)
appendFromNewPending(m_postMine.oldBloom(i), changeds);
appendFromNewPending(m_postMine.logBloom(i), changeds);
changeds.insert(PendingChangedFilter);
m_postMine = m_preMine;
}
@ -181,7 +181,7 @@ unsigned Client::installWatch(h256 _h)
return ret;
}
unsigned Client::installWatch(MessageFilter const& _f)
unsigned Client::installWatch(LogFilter const& _f)
{
lock_guard<mutex> l(m_filterLock);
@ -222,8 +222,9 @@ void Client::noteChanged(h256Set const& _filters)
}
}
void Client::appendFromNewPending(h256 _bloom, h256Set& o_changed) const
void Client::appendFromNewPending(LogBloom _bloom, h256Set& o_changed) const
{
// TODO: more precise check on whether the txs match.
lock_guard<mutex> l(m_filterLock);
for (pair<h256, InstalledFilter> const& i: m_filters)
if ((unsigned)i.second.filter.latest() > m_bc.number() && i.second.filter.matches(_bloom))
@ -232,11 +233,12 @@ void Client::appendFromNewPending(h256 _bloom, h256Set& o_changed) const
void Client::appendFromNewBlock(h256 _block, h256Set& o_changed) const
{
auto d = m_bc.details(_block);
// TODO: more precise check on whether the txs match.
auto d = m_bc.info(_block);
lock_guard<mutex> l(m_filterLock);
for (pair<h256, InstalledFilter> const& i: m_filters)
if ((unsigned)i.second.filter.latest() >= d.number && (unsigned)i.second.filter.earliest() <= d.number && i.second.filter.matches(d.bloom))
if ((unsigned)i.second.filter.latest() >= d.number && (unsigned)i.second.filter.earliest() <= d.number && i.second.filter.matches(d.logBloom))
o_changed.insert(i.first);
}
@ -341,7 +343,7 @@ bytes Client::call(Secret _secret, u256 _value, Address _dest, bytes const& _dat
n = temp.transactionsFrom(toAddress(_secret));
}
Transaction t(_value, _gasPrice, _gas, _dest, _data, n, _secret);
u256 gasUsed = temp.execute(t.data(), &out, false);
u256 gasUsed = temp.execute(t.rlp(), &out, false);
(void)gasUsed; // TODO: do something with gasused which it returns.
}
catch (...)
@ -440,7 +442,7 @@ void Client::doWork()
// returns h256s as blooms, once for each transaction.
cwork << "postSTATE <== TQ";
h256s newPendingBlooms = m_postMine.sync(m_tq);
h512s newPendingBlooms = m_postMine.sync(m_tq);
if (newPendingBlooms.size())
{
for (auto i: newPendingBlooms)
@ -564,9 +566,9 @@ BlockInfo Client::uncle(h256 _blockHash, unsigned _i) const
return BlockInfo::fromHeader(b[2][_i].data());
}
PastMessages Client::messages(MessageFilter const& _f) const
LogEntries Client::logs(LogFilter const& _f) const
{
PastMessages ret;
LogEntries ret;
unsigned begin = min<unsigned>(m_bc.number(), (unsigned)_f.latest());
unsigned end = min(begin, (unsigned)_f.earliest());
unsigned m = _f.max();
@ -578,23 +580,22 @@ PastMessages Client::messages(MessageFilter const& _f) const
ReadGuard l(x_stateDB);
for (unsigned i = 0; i < m_postMine.pending().size(); ++i)
{
// Might have a transaction that contains a matching message.
Manifest const& ms = m_postMine.changesFromPending(i);
PastMessages pm = _f.matches(ms, i);
if (pm.size())
// Might have a transaction that contains a matching log.
TransactionReceipt const& tr = m_postMine.receipt(i);
LogEntries le = _f.matches(tr);
if (le.size())
{
auto ts = time(0);
for (unsigned j = 0; j < pm.size() && ret.size() != m; ++j)
for (unsigned j = 0; j < le.size() && ret.size() != m; ++j)
if (s)
s--;
else
// Have a transaction that contains a matching message.
ret.insert(ret.begin(), pm[j].polish(h256(), ts, m_bc.number() + 1, m_postMine.address()));
ret.insert(ret.begin(), le[j]);
}
}
}
#if ETH_DEBUG
// fill these params
unsigned skipped = 0;
unsigned falsePos = 0;
#endif
@ -602,55 +603,40 @@ PastMessages Client::messages(MessageFilter const& _f) const
unsigned n = begin;
for (; ret.size() != m && n != end; n--, h = m_bc.details(h).parent)
{
auto d = m_bc.details(h);
#if ETH_DEBUG
int total = 0;
#endif
if (_f.matches(d.bloom))
{
// Might have a block that contains a transaction that contains a matching message.
auto bs = m_bc.blooms(h).blooms;
Manifests ms;
BlockInfo bi;
for (unsigned i = 0; i < bs.size(); ++i)
if (_f.matches(bs[i]))
{
// Might have a transaction that contains a matching message.
if (ms.empty())
ms = m_bc.traces(h).traces;
Manifest const& changes = ms[i];
PastMessages pm = _f.matches(changes, i);
if (pm.size())
// check block bloom
if (_f.matches(m_bc.info(h).logBloom))
for (TransactionReceipt receipt: m_bc.receipts(h).receipts)
{
if (_f.matches(receipt.bloom()))
{
LogEntries le = _f.matches(receipt);
if (le.size())
{
#if ETH_DEBUG
total += pm.size();
total += le.size();
#endif
if (!bi)
bi.populate(m_bc.block(h));
auto ts = bi.timestamp;
auto cb = bi.coinbaseAddress;
for (unsigned j = 0; j < pm.size() && ret.size() != m; ++j)
for (unsigned j = 0; j < le.size() && ret.size() != m; ++j)
{
if (s)
s--;
else
// Have a transaction that contains a matching message.
ret.push_back(pm[j].polish(h, ts, n, cb));
ret.insert(ret.begin(), le[j]);
}
}
}
#if ETH_DEBUG
if (!total)
falsePos++;
}
else
skipped++;
#else
}
#endif
if (n == end)
break;
}
#if ETH_DEBUG
// cdebug << (begin - n) << "searched; " << skipped << "skipped; " << falsePos << "false +ves";
cdebug << (begin - n) << "searched; " << skipped << "skipped; " << falsePos << "false +ves";
#endif
return ret;
}

14
libethereum/Client.h

@ -79,9 +79,11 @@ static const int GenesisBlock = INT_MIN;
struct InstalledFilter
{
InstalledFilter(MessageFilter const& _f): filter(_f) {}
// InstalledFilter(MessageFilter const& _f): filter(_f) {}
// MessageFilter filter;
InstalledFilter(LogFilter const& _f): filter(_f) {}
MessageFilter filter;
LogFilter filter;
unsigned refCount = 1;
};
@ -152,14 +154,14 @@ public:
virtual bytes codeAt(Address _a, int _block) const;
virtual std::map<u256, u256> storageAt(Address _a, int _block) const;
virtual unsigned installWatch(MessageFilter const& _filter);
virtual unsigned installWatch(LogFilter const& _filter);
virtual unsigned installWatch(h256 _filterId);
virtual void uninstallWatch(unsigned _watchId);
virtual bool peekWatch(unsigned _watchId) const { std::lock_guard<std::mutex> l(m_filterLock); try { return m_watches.at(_watchId).changes != 0; } catch (...) { return false; } }
virtual bool checkWatch(unsigned _watchId) { std::lock_guard<std::mutex> l(m_filterLock); bool ret = false; try { ret = m_watches.at(_watchId).changes != 0; m_watches.at(_watchId).changes = 0; } catch (...) {} return ret; }
virtual PastMessages messages(unsigned _watchId) const { try { std::lock_guard<std::mutex> l(m_filterLock); return messages(m_filters.at(m_watches.at(_watchId).id).filter); } catch (...) { return PastMessages(); } }
virtual PastMessages messages(MessageFilter const& _filter) const;
virtual LogEntries logs(unsigned _watchId) const { try { std::lock_guard<std::mutex> l(m_filterLock); return logs(m_filters.at(m_watches.at(_watchId).id).filter); } catch (...) { return LogEntries(); } }
virtual LogEntries logs(LogFilter const& _filter) const;
// [EXTRA API]:
@ -259,7 +261,7 @@ private:
/// Collate the changed filters for the bloom filter of the given pending transaction.
/// Insert any filters that are activated into @a o_changed.
void appendFromNewPending(h256 _pendingTransactionBloom, h256Set& o_changed) const;
void appendFromNewPending(LogBloom _pendingTransactionBloom, h256Set& o_changed) const;
/// Collate the changed filters for the hash of the given block.
/// Insert any filters that are activated into @a o_changed.

18
libethereum/Interface.h

@ -84,13 +84,18 @@ public:
virtual bytes codeAt(Address _a, int _block) const = 0;
virtual std::map<u256, u256> storageAt(Address _a, int _block) const = 0;
// [MESSAGE API]
// // [MESSAGE API]
//
// virtual PastMessages messages(unsigned _watchId) const = 0;
// virtual PastMessages messages(MessageFilter const& _filter) const = 0;
virtual PastMessages messages(unsigned _watchId) const = 0;
virtual PastMessages messages(MessageFilter const& _filter) const = 0;
// [LOGS API]
virtual LogEntries logs(unsigned _watchId) const = 0;
virtual LogEntries logs(LogFilter const& _filter) const = 0;
/// Install, uninstall and query watches.
virtual unsigned installWatch(MessageFilter const& _filter) = 0;
virtual unsigned installWatch(LogFilter const& _filter) = 0;
virtual unsigned installWatch(h256 _filterId) = 0;
virtual void uninstallWatch(unsigned _watchId) = 0;
virtual bool peekWatch(unsigned _watchId) const = 0;
@ -175,12 +180,13 @@ class Watch: public boost::noncopyable
public:
Watch() {}
Watch(Interface& _c, h256 _f): m_c(&_c), m_id(_c.installWatch(_f)) {}
Watch(Interface& _c, MessageFilter const& _tf): m_c(&_c), m_id(_c.installWatch(_tf)) {}
Watch(Interface& _c, LogFilter const& _tf): m_c(&_c), m_id(_c.installWatch(_tf)) {}
~Watch() { if (m_c) m_c->uninstallWatch(m_id); }
bool check() { return m_c ? m_c->checkWatch(m_id) : false; }
bool peek() { return m_c ? m_c->peekWatch(m_id) : false; }
PastMessages messages() const { return m_c->messages(m_id); }
// PastMessages messages() const { return m_c->messages(m_id); }
LogEntries logs() const { return m_c->logs(m_id); }
private:
Interface* m_c = nullptr;

1
libethereum/MessageFilter.h

@ -90,7 +90,6 @@ public:
LogEntries matches(TransactionReceipt const& _r) const;
LogFilter address(Address _a) { m_addresses.insert(_a); return *this; }
LogFilter from(Address _a) { return topic(u256((u160)_a) + 1); }
LogFilter topic(h256 const& _t) { m_topics.insert(_t); return *this; }
LogFilter withMax(unsigned _m) { m_max = _m; return *this; }
LogFilter withSkip(unsigned _m) { m_skip = _m; return *this; }

10
libethereum/State.cpp

@ -534,10 +534,10 @@ bool State::cull(TransactionQueue& _tq) const
return ret;
}
h256s State::sync(TransactionQueue& _tq, bool* o_transactionQueueChanged)
h512s State::sync(TransactionQueue& _tq, bool* o_transactionQueueChanged)
{
// TRANSACTIONS
h256s ret;
h512s ret;
auto ts = _tq.transactions();
for (int goodTxs = 1; goodTxs;)
@ -552,7 +552,7 @@ h256s State::sync(TransactionQueue& _tq, bool* o_transactionQueueChanged)
uncommitToMine();
// boost::timer t;
execute(i.second);
ret.push_back(m_receipts.back().changes().bloom());
ret.push_back(m_receipts.back().bloom());
_tq.noteGood(i);
++goodTxs;
// cnote << "TX took:" << t.elapsed() * 1000;
@ -802,7 +802,7 @@ void State::commitToMine(BlockChain const& _bc)
{
uncommitToMine();
cnote << "Committing to mine on block" << m_previousBlock.hash.abridged();
// cnote << "Committing to mine on block" << m_previousBlock.hash.abridged();
#ifdef ETH_PARANOIA
commit();
cnote << "Pre-reward stateRoot:" << m_state.root();
@ -877,7 +877,7 @@ void State::commitToMine(BlockChain const& _bc)
// Commit any and all changes to the trie that are in the cache, then update the state root accordingly.
commit();
cnote << "Post-reward stateRoot:" << m_state.root().abridged();
// cnote << "Post-reward stateRoot:" << m_state.root().abridged();
// cnote << m_state;
// cnote << *this;

2
libethereum/State.h

@ -147,7 +147,7 @@ public:
/// @returns a list of bloom filters one for each transaction placed from the queue into the state.
/// @a o_transactionQueueChanged boolean pointer, the value of which will be set to true if the transaction queue
/// changed and the pointer is non-null
h256s sync(TransactionQueue& _tq, bool* o_transactionQueueChanged = nullptr);
h512s sync(TransactionQueue& _tq, bool* o_transactionQueueChanged = nullptr);
/// Like sync but only operate on _tq, killing the invalid/old ones.
bool cull(TransactionQueue& _tq) const;

1068
libjsqrc/ethereum.js

File diff suppressed because it is too large

3
libjsqrc/js.qrc

@ -2,7 +2,6 @@
<qresource prefix="/js">
<file>es6-promise-2.0.0.js</file>
<file>setup.js</file>
<file>main.js</file>
<file>qt.js</file>
<file>ethereum.js</file>
</qresource>
</RCC>

467
libjsqrc/main.js

@ -1,467 +0,0 @@
/*
This file is part of ethereum.js.
ethereum.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ethereum.js 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file main.js
* @authors:
* Marek Kotewicz <marek@ethdev.com>
* @date 2014
*/
(function(window) {
function isPromise(o) {
return o instanceof Promise
}
function flattenPromise (obj) {
if (obj instanceof Promise) {
return Promise.resolve(obj);
}
if (obj instanceof Array) {
return new Promise(function (resolve) {
var promises = obj.map(function (o) {
return flattenPromise(o);
});
return Promise.all(promises).then(function (res) {
for (var i = 0; i < obj.length; i++) {
obj[i] = res[i];
}
resolve(obj);
});
});
}
if (obj instanceof Object) {
return new Promise(function (resolve) {
var keys = Object.keys(obj);
var promises = keys.map(function (key) {
return flattenPromise(obj[key]);
});
return Promise.all(promises).then(function (res) {
for (var i = 0; i < keys.length; i++) {
obj[keys[i]] = res[i];
}
resolve(obj);
});
});
}
return Promise.resolve(obj);
};
var ethMethods = function () {
var blockCall = function (args) {
return typeof args[0] === "string" ? "eth_blockByHash" : "eth_blockByNumber";
};
var transactionCall = function (args) {
return typeof args[0] === "string" ? 'eth_transactionByHash' : 'eth_transactionByNumber';
};
var uncleCall = function (args) {
return typeof args[0] === "string" ? 'eth_uncleByHash' : 'eth_uncleByNumber';
};
var methods = [
{ name: 'balanceAt', call: 'eth_balanceAt' },
{ name: 'stateAt', call: 'eth_stateAt' },
{ name: 'countAt', call: 'eth_countAt'},
{ name: 'codeAt', call: 'eth_codeAt' },
{ name: 'transact', call: 'eth_transact' },
{ name: 'call', call: 'eth_call' },
{ name: 'block', call: blockCall },
{ name: 'transaction', call: transactionCall },
{ name: 'uncle', call: uncleCall },
{ name: 'compile', call: 'eth_compile' },
{ name: 'lll', call: 'eth_lll' }
];
return methods;
};
var ethProperties = function () {
return [
{ name: 'coinbase', getter: 'eth_coinbase', setter: 'eth_setCoinbase' },
{ name: 'listening', getter: 'eth_listening', setter: 'eth_setListening' },
{ name: 'mining', getter: 'eth_mining', setter: 'eth_setMining' },
{ name: 'gasPrice', getter: 'eth_gasPrice' },
{ name: 'account', getter: 'eth_account' },
{ name: 'accounts', getter: 'eth_accounts' },
{ name: 'peerCount', getter: 'eth_peerCount' },
{ name: 'defaultBlock', getter: 'eth_defaultBlock', setter: 'eth_setDefaultBlock' },
{ name: 'number', getter: 'eth_number'}
];
};
var dbMethods = function () {
return [
{ name: 'put', call: 'db_put' },
{ name: 'get', call: 'db_get' },
{ name: 'putString', call: 'db_putString' },
{ name: 'getString', call: 'db_getString' }
];
};
var shhMethods = function () {
return [
{ name: 'post', call: 'shh_post' },
{ name: 'newIdentity', call: 'shh_newIdentity' },
{ name: 'haveIdentity', call: 'shh_haveIdentity' },
{ name: 'newGroup', call: 'shh_newGroup' },
{ name: 'addToGroup', call: 'shh_addToGroup' }
];
};
var ethWatchMethods = function () {
var newFilter = function (args) {
return typeof args[0] === 'string' ? 'eth_newFilterString' : 'eth_newFilter';
};
return [
{ name: 'newFilter', call: newFilter },
{ name: 'uninstallFilter', call: 'eth_uninstallFilter' },
{ name: 'getMessages', call: 'eth_getMessages' }
];
};
var shhWatchMethods = function () {
return [
{ name: 'newFilter', call: 'shh_newFilter' },
{ name: 'uninstallFilter', call: 'shh_uninstallFilter' },
{ name: 'getMessage', call: 'shh_getMessages' }
];
};
var setupMethods = function (obj, methods) {
methods.forEach(function (method) {
obj[method.name] = function () {
return flattenPromise(Array.prototype.slice.call(arguments)).then(function (args) {
var call = typeof method.call === "function" ? method.call(args) : method.call;
return {call: call, args: args};
}).then(function (request) {
return new Promise(function (resolve, reject) {
web3.provider.send(request, function (err, result) {
if (!err) {
resolve(result);
return;
}
reject(err);
});
});
}).catch(function(err) {
console.error(err);
});
};
});
};
var setupProperties = function (obj, properties) {
properties.forEach(function (property) {
var proto = {};
proto.get = function () {
return new Promise(function(resolve, reject) {
web3.provider.send({call: property.getter}, function(err, result) {
if (!err) {
resolve(result);
return;
}
reject(err);
});
});
};
if (property.setter) {
proto.set = function (val) {
return flattenPromise([val]).then(function (args) {
return new Promise(function (resolve) {
web3.provider.send({call: property.setter, args: args}, function (err, result) {
if (!err) {
resolve(result);
return;
}
reject(err);
});
});
}).catch(function (err) {
console.error(err);
});
}
}
Object.defineProperty(obj, property.name, proto);
});
};
var web3 = {
_callbacks: {},
_events: {},
providers: {},
toHex: function(str) {
var hex = "";
for(var i = 0; i < str.length; i++) {
var n = str.charCodeAt(i).toString(16);
hex += n.length < 2 ? '0' + n : n;
}
return hex;
},
toAscii: function(hex) {
// Find termination
var str = "";
var i = 0, l = hex.length;
if (hex.substring(0, 2) == '0x')
i = 2;
for(; i < l; i+=2) {
var code = hex.charCodeAt(i)
if(code == 0) {
break;
}
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
}
return str;
},
toDecimal: function (val) {
return parseInt(val, 16);
},
fromAscii: function(str, pad) {
pad = pad === undefined ? 32 : pad;
var hex = this.toHex(str);
while(hex.length < pad*2)
hex += "00";
return "0x" + hex;
},
eth: {
prototype: Object(),
watch: function (params) {
return new Filter(params, ethWatch);
},
},
db: {
prototype: Object()
},
shh: {
prototype: Object(),
watch: function (params) {
return new Filter(params, shhWatch);
}
},
on: function(event, id, cb) {
if(web3._events[event] === undefined) {
web3._events[event] = {};
}
web3._events[event][id] = cb;
return this
},
off: function(event, id) {
if(web3._events[event] !== undefined) {
delete web3._events[event][id];
}
return this
},
trigger: function(event, id, data) {
var callbacks = web3._events[event];
if (!callbacks || !callbacks[id]) {
return;
}
var cb = callbacks[id];
cb(data);
},
};
var eth = web3.eth;
setupMethods(eth, ethMethods());
setupProperties(eth, ethProperties());
setupMethods(web3.db, dbMethods());
setupMethods(web3.shh, shhMethods());
var ethWatch = {
changed: 'eth_changed'
};
setupMethods(ethWatch, ethWatchMethods());
var shhWatch = {
changed: 'shh_changed'
};
setupMethods(shhWatch, shhWatchMethods());
var ProviderManager = function() {
this.queued = [];
this.polls = [];
this.ready = false;
this.provider = undefined;
this.id = 1;
var self = this;
var poll = function () {
if (self.provider && self.provider.poll) {
self.polls.forEach(function (data) {
data.data._id = self.id;
self.id++;
self.provider.poll(data.data, data.id);
});
}
setTimeout(poll, 12000);
};
poll();
};
ProviderManager.prototype.send = function(data, cb) {
data._id = this.id;
if (cb) {
web3._callbacks[data._id] = cb;
}
data.args = data.args || [];
this.id++;
if(this.provider !== undefined) {
this.provider.send(data);
} else {
console.warn("provider is not set");
this.queued.push(data);
}
};
ProviderManager.prototype.set = function(provider) {
if(this.provider !== undefined && this.provider.unload !== undefined) {
this.provider.unload();
}
this.provider = provider;
this.ready = true;
};
ProviderManager.prototype.sendQueued = function() {
for(var i = 0; this.queued.length; i++) {
// Resend
this.send(this.queued[i]);
}
};
ProviderManager.prototype.installed = function() {
return this.provider !== undefined;
};
ProviderManager.prototype.startPolling = function (data, pollId) {
if (!this.provider || !this.provider.poll) {
return;
}
this.polls.push({data: data, id: pollId});
};
ProviderManager.prototype.stopPolling = function (pollId) {
for (var i = this.polls.length; i--;) {
var poll = this.polls[i];
if (poll.id === pollId) {
this.polls.splice(i, 1);
}
}
};
web3.provider = new ProviderManager();
web3.setProvider = function(provider) {
provider.onmessage = messageHandler;
web3.provider.set(provider);
web3.provider.sendQueued();
};
var Filter = function(options, impl) {
this.impl = impl;
this.callbacks = [];
var self = this;
this.promise = impl.newFilter(options);
this.promise.then(function (id) {
self.id = id;
web3.on(impl.changed, id, self.trigger.bind(self));
web3.provider.startPolling({call: impl.changed, args: [id]}, id);
});
};
Filter.prototype.arrived = function(callback) {
this.changed(callback);
}
Filter.prototype.changed = function(callback) {
var self = this;
this.promise.then(function(id) {
self.callbacks.push(callback);
});
};
Filter.prototype.trigger = function(messages) {
if (!(messages instanceof Array) || messages.length) {
for(var i = 0; i < this.callbacks.length; i++) {
this.callbacks[i].call(this, messages);
}
}
};
Filter.prototype.uninstall = function() {
var self = this;
this.promise.then(function (id) {
self.impl.uninstallFilter(id);
web3.provider.stopPolling(id);
web3.off(impl.changed, id);
});
};
Filter.prototype.messages = function() {
var self = this;
return this.promise.then(function (id) {
return self.impl.getMessages(id);
});
};
function messageHandler(data) {
if(data._event !== undefined) {
web3.trigger(data._event, data._id, data.data);
return;
}
if(data._id) {
var cb = web3._callbacks[data._id];
if (cb) {
cb.call(this, data.error, data.data);
delete web3._callbacks[data._id];
}
}
}
/*
// Install default provider
if(!web3.provider.installed()) {
var sock = new web3.WebSocket("ws://localhost:40404/eth");
web3.setProvider(sock);
}
*/
window.web3 = web3;
})(this);

49
libjsqrc/qt.js

@ -1,49 +0,0 @@
/*
This file is part of ethereum.js.
ethereum.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ethereum.js 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file qt.js
* @authors:
* Marek Kotewicz <marek@ethdev.com>
* @date 2014
*/
(function() {
var QtProvider = function() {
this.handlers = [];
var self = this;
navigator.qt.onmessage = function (message) {
self.handlers.forEach(function (handler) {
handler.call(self, JSON.parse(message.data));
});
}
};
QtProvider.prototype.send = function(payload) {
navigator.qt.postMessage(JSON.stringify(payload));
};
Object.defineProperty(QtProvider.prototype, "onmessage", {
set: function(handler) {
this.handlers.push(handler);
},
});
if(typeof(web3) !== "undefined" && web3.providers !== undefined) {
web3.providers.QtProvider = QtProvider;
}
})();

2
libjsqrc/setup.js

@ -41,4 +41,6 @@ if (window.Promise === undefined) {
window.Promise = ES6Promise.Promise;
}
var web3 = require('web3');
web3.setProvider(new web3.providers.QtProvider());

3
libqethereum/QEthereum.h

@ -85,8 +85,7 @@ private:
_frame->addToJavaScriptWindowObject("_web3", qweb, QWebFrame::ScriptOwnership); \
_frame->addToJavaScriptWindowObject("env", _env, QWebFrame::QtOwnership); \
_frame->evaluateJavaScript(contentsOfQResource(":/js/es6-promise-2.0.0.js")); \
_frame->evaluateJavaScript(contentsOfQResource(":/js/main.js")); \
_frame->evaluateJavaScript(contentsOfQResource(":/js/qt.js")); \
_frame->evaluateJavaScript(contentsOfQResource(":/js/ethereum.js")); \
_frame->evaluateJavaScript(contentsOfQResource(":/js/setup.js")); \
}

2
libweb3jsonrpc/CMakeLists.txt

@ -18,6 +18,8 @@ endif()
target_link_libraries(${EXECUTABLE} webthree)
target_link_libraries(${EXECUTABLE} secp256k1)
target_link_libraries(${EXECUTABLE} gmp)
target_link_libraries(${EXECUTABLE} solidity)
target_link_libraries(${EXECUTABLE} serpent)
if(MINIUPNPC_LS)
target_link_libraries(${EXECUTABLE} ${MINIUPNPC_LS})
endif()

236
libweb3jsonrpc/WebThreeStubServer.cpp

@ -31,6 +31,10 @@
#include <libdevcrypto/FileSystem.h>
#include <libwhisper/Message.h>
#include <libwhisper/WhisperHost.h>
#include <libsolidity/CompilerStack.h>
#include <libsolidity/Scanner.h>
#include <libsolidity/SourceReferenceFormatter.h>
#include <libserpent/funcs.h>
using namespace std;
using namespace dev;
@ -55,34 +59,6 @@ static Json::Value toJson(dev::eth::BlockInfo const& _bi)
return res;
}
static Json::Value toJson(dev::eth::PastMessage const& _t)
{
Json::Value res;
res["input"] = jsFromBinary(_t.input);
res["output"] = jsFromBinary(_t.output);
res["to"] = toJS(_t.to);
res["from"] = toJS(_t.from);
res["value"] = jsToDecimal(toJS(_t.value));
res["origin"] = toJS(_t.origin);
res["timestamp"] = toJS(_t.timestamp);
res["coinbase"] = toJS(_t.coinbase);
res["block"] = toJS(_t.block);
Json::Value path;
for (int i: _t.path)
path.append(i);
res["path"] = path;
res["number"] = (int)_t.number;
return res;
}
static Json::Value toJson(dev::eth::PastMessages const& _pms)
{
Json::Value res;
for (dev::eth::PastMessage const& t: _pms)
res.append(toJson(t));
return res;
}
static Json::Value toJson(dev::eth::Transaction const& _t)
{
Json::Value res;
@ -100,6 +76,7 @@ static Json::Value toJson(dev::eth::Transaction const& _t)
static Json::Value toJson(dev::eth::LogEntry const& _e)
{
Json::Value res;
res["data"] = jsFromBinary(_e.data);
res["address"] = toJS(_e.address);
for (auto const& t: _e.topics)
@ -107,7 +84,7 @@ static Json::Value toJson(dev::eth::LogEntry const& _e)
return res;
}
/*static*/ Json::Value toJson(dev::eth::LogEntries const& _es) // commented to avoid warning. Uncomment once in use @ poC-7.
static Json::Value toJson(dev::eth::LogEntries const& _es) // commented to avoid warning. Uncomment once in use @ poC-7.
{
Json::Value res;
for (dev::eth::LogEntry const& e: _es)
@ -115,81 +92,38 @@ static Json::Value toJson(dev::eth::LogEntry const& _e)
return res;
}
static dev::eth::MessageFilter toMessageFilter(Json::Value const& _json)
static Json::Value toJson(std::map<u256, u256> const& _storage)
{
dev::eth::MessageFilter filter;
if (!_json.isObject() || _json.empty())
return filter;
if (!_json["earliest"].empty())
filter.withEarliest(_json["earliest"].asInt());
if (!_json["latest"].empty())
filter.withLatest(_json["lastest"].asInt());
if (!_json["max"].empty())
filter.withMax(_json["max"].asInt());
if (!_json["skip"].empty())
filter.withSkip(_json["skip"].asInt());
if (!_json["from"].empty())
{
if (_json["from"].isArray())
for (auto i : _json["from"])
filter.from(jsToAddress(i.asString()));
else
filter.from(jsToAddress(_json["from"].asString()));
}
if (!_json["to"].empty())
{
if (_json["to"].isArray())
for (auto i : _json["to"])
filter.to(jsToAddress(i.asString()));
else
filter.to(jsToAddress(_json["to"].asString()));
}
if (!_json["altered"].empty())
{
if (_json["altered"].isArray())
for (auto i: _json["altered"])
if (i.isObject())
filter.altered(jsToAddress(i["id"].asString()), jsToU256(i["at"].asString()));
else
filter.altered((jsToAddress(i.asString())));
else if (_json["altered"].isObject())
filter.altered(jsToAddress(_json["altered"]["id"].asString()), jsToU256(_json["altered"]["at"].asString()));
else
filter.altered(jsToAddress(_json["altered"].asString()));
}
return filter;
Json::Value res(Json::objectValue);
for (auto i: _storage)
res[toJS(i.first)] = toJS(i.second);
return res;
}
/*static*/ dev::eth::LogFilter toLogFilter(Json::Value const& _json) // commented to avoid warning. Uncomment once in use @ PoC-7.
static dev::eth::LogFilter toLogFilter(Json::Value const& _json) // commented to avoid warning. Uncomment once in use @ PoC-7.
{
dev::eth::LogFilter filter;
if (!_json.isObject() || _json.empty())
return filter;
if (!_json["earliest"].empty())
if (_json["earliest"].isInt())
filter.withEarliest(_json["earliest"].asInt());
if (!_json["latest"].empty())
if (_json["latest"].isInt())
filter.withLatest(_json["lastest"].asInt());
if (!_json["max"].empty())
if (_json["max"].isInt())
filter.withMax(_json["max"].asInt());
if (!_json["skip"].empty())
if (_json["skip"].isInt())
filter.withSkip(_json["skip"].asInt());
if (!_json["from"].empty())
{
if (_json["from"].isArray())
for (auto i : _json["from"])
filter.from(jsToAddress(i.asString()));
else
filter.from(jsToAddress(_json["from"].asString()));
}
if (!_json["address"].empty())
{
if (_json["address"].isArray())
{
for (auto i : _json["address"])
if (i.isString())
filter.address(jsToAddress(i.asString()));
else
filter.from(jsToAddress(_json["address"].asString()));
}
else if (_json["address"].isString())
filter.address(jsToAddress(_json["address"].asString()));
}
if (!_json["topics"].empty())
{
@ -208,11 +142,11 @@ static dev::eth::MessageFilter toMessageFilter(Json::Value const& _json)
static shh::Message toMessage(Json::Value const& _json)
{
shh::Message ret;
if (!_json["from"].empty())
if (_json["from"].isString())
ret.setFrom(jsToPublic(_json["from"].asString()));
if (!_json["to"].empty())
if (_json["to"].isString())
ret.setTo(jsToPublic(_json["to"].asString()));
if (!_json["payload"].empty())
if (_json["payload"].isString())
ret.setPayload(jsToBytes(_json["payload"].asString()));
return ret;
}
@ -223,9 +157,9 @@ static shh::Envelope toSealed(Json::Value const& _json, shh::Message const& _m,
unsigned workToProve = 50;
shh::BuildTopic bt;
if (!_json["ttl"].empty())
if (_json["ttl"].isInt())
ttl = _json["ttl"].asInt();
if (!_json["workToProve"].empty())
if (_json["workToProve"].isInt())
workToProve = _json["workToProve"].asInt();
if (!_json["topic"].empty())
{
@ -233,6 +167,7 @@ static shh::Envelope toSealed(Json::Value const& _json, shh::Message const& _m,
bt.shift(jsToBytes(_json["topic"].asString()));
else if (_json["topic"].isArray())
for (auto i: _json["topic"])
if (i.isString())
bt.shift(jsToBytes(i.asString()));
}
return _m.seal(_from, bt, ttl, workToProve);
@ -243,7 +178,7 @@ static pair<shh::TopicMask, Public> toWatch(Json::Value const& _json)
shh::BuildTopicMask bt;
Public to;
if (!_json["to"].empty())
if (_json["to"].isString())
to = jsToPublic(_json["to"].asString());
if (!_json["topic"].empty())
@ -351,33 +286,42 @@ static TransactionSkeleton toTransaction(Json::Value const& _json)
if (!_json.isObject() || _json.empty())
return ret;
if (!_json["from"].empty())
if (_json["from"].isString())
ret.from = jsToAddress(_json["from"].asString());
if (!_json["to"].empty())
if (_json["to"].isString())
ret.to = jsToAddress(_json["to"].asString());
if (!_json["value"].empty())
{
if (_json["value"].isString())
ret.value = jsToU256(_json["value"].asString());
else if (_json["value"].isInt())
ret.value = u256(_json["value"].asInt());
}
if (!_json["gas"].empty())
{
if (_json["gas"].isString())
ret.gas = jsToU256(_json["gas"].asString());
else if (_json["gas"].isInt())
ret.gas = u256(_json["gas"].asInt());
}
if (!_json["gasPrice"].empty())
{
if (_json["gasPrice"].isString())
ret.gasPrice = jsToU256(_json["gasPrice"].asString());
if (!_json["data"].empty() || _json["code"].empty() || _json["dataclose"].empty())
else if (_json["gasPrice"].isInt())
ret.gas = u256(_json["gas"].asInt());
}
if (!_json["data"].empty())
{
if (_json["data"].isString())
if (_json["data"].isString()) // ethereum.js has preconstructed the data array
ret.data = jsToBytes(_json["data"].asString());
else if (_json["code"].isString())
ret.data = jsToBytes(_json["code"].asString());
else if (_json["data"].isArray())
else if (_json["data"].isArray()) // old style: array of 32-byte-padded values. TODO: remove PoC-8
for (auto i: _json["data"])
dev::operator +=(ret.data, padded(jsToBytes(i.asString()), 32));
else if (_json["code"].isArray())
for (auto i: _json["code"])
dev::operator +=(ret.data, padded(jsToBytes(i.asString()), 32));
else if (_json["dataclose"].isArray())
for (auto i: _json["dataclose"])
dev::operator +=(ret.data, jsToBytes(i.asString()));
}
if (_json["code"].isString())
ret.data = jsToBytes(_json["code"].asString());
return ret;
}
@ -447,11 +391,18 @@ std::string WebThreeStubServer::db_get(std::string const& _name, std::string con
return toJS(dev::asBytes(ret));
}
Json::Value WebThreeStubServer::eth_getMessages(int const& _id)
Json::Value WebThreeStubServer::eth_filterLogs(int const& _id)
{
if (!client())
return Json::Value(Json::arrayValue);
return toJson(client()->logs(_id));
}
Json::Value WebThreeStubServer::eth_logs(Json::Value const& _json)
{
if (!client())
return Json::Value();
return toJson(client()->messages(_id));
return Json::Value(Json::arrayValue);
return toJson(client()->logs(toLogFilter(_json)));
}
std::string WebThreeStubServer::db_getString(std::string const& _name, std::string const& _key)
@ -482,7 +433,8 @@ int WebThreeStubServer::eth_newFilter(Json::Value const& _json)
unsigned ret = -1;
if (!client())
return ret;
ret = client()->installWatch(toMessageFilter(_json));
// ret = client()->installWatch(toMessageFilter(_json));
ret = client()->installWatch(toLogFilter(_json));
return ret;
}
@ -513,14 +465,61 @@ std::string WebThreeStubServer::shh_newIdentity()
return toJS(kp.pub());
}
std::string WebThreeStubServer::eth_compile(string const& _s)
Json::Value WebThreeStubServer::eth_compilers()
{
Json::Value ret(Json::arrayValue);
ret.append("lll");
ret.append("solidity");
ret.append("serpent");
return ret;
}
std::string WebThreeStubServer::eth_lll(std::string const& _code)
{
string res;
vector<string> errors;
res = toJS(dev::eth::compileLLL(_code, true, &errors));
cwarn << "LLL compilation errors: " << errors;
return res;
}
std::string WebThreeStubServer::eth_serpent(std::string const& _code)
{
return toJS(dev::eth::compileLLL(_s));
string res;
try
{
res = toJS(dev::asBytes(::compile(_code)));
}
catch (string err)
{
cwarn << "Solidity compilation error: " << err;
}
catch (...)
{
cwarn << "Uncought serpent compilation exception";
}
return res;
}
std::string WebThreeStubServer::eth_lll(string const& _s)
std::string WebThreeStubServer::eth_solidity(std::string const& _code)
{
return toJS(dev::eth::compileLLL(_s));
string res;
dev::solidity::CompilerStack compiler;
try
{
res = toJS(compiler.compile(_code, true));
}
catch (dev::Exception const& exception)
{
ostringstream error;
solidity::SourceReferenceFormatter::printExceptionInformation(error, exception, "Error", compiler.getScanner());
cwarn << "Solidity compilation error: " << error.str();
}
catch (...)
{
cwarn << "Uncought solidity compilation exception";
}
return res;
}
int WebThreeStubServer::eth_number()
@ -647,6 +646,13 @@ std::string WebThreeStubServer::eth_stateAt(string const& _address, string const
return client() ? toJS(client()->stateAt(jsToAddress(_address), jsToU256(_storage), block)) : "";
}
Json::Value WebThreeStubServer::eth_storageAt(string const& _address)
{
if (!client())
return Json::Value(Json::objectValue);
return toJson(client()->storageAt(jsToAddress(_address)));
}
std::string WebThreeStubServer::eth_transact(Json::Value const& _json)
{
std::string ret;

8
libweb3jsonrpc/WebThreeStubServer.h

@ -72,11 +72,12 @@ public:
virtual bool eth_changed(int const& _id);
virtual std::string eth_codeAt(std::string const& _address);
virtual std::string eth_coinbase();
virtual std::string eth_compile(std::string const& _s);
virtual Json::Value eth_compilers();
virtual double eth_countAt(std::string const& _address);
virtual int eth_defaultBlock();
virtual std::string eth_gasPrice();
virtual Json::Value eth_getMessages(int const& _id);
virtual Json::Value eth_filterLogs(int const& _id);
virtual Json::Value eth_logs(Json::Value const& _json);
virtual bool eth_listening();
virtual bool eth_mining();
virtual int eth_newFilter(Json::Value const& _json);
@ -87,8 +88,11 @@ public:
virtual bool eth_setDefaultBlock(int const& _block);
virtual bool eth_setListening(bool const& _listening);
virtual std::string eth_lll(std::string const& _s);
virtual std::string eth_serpent(std::string const& _s);
virtual bool eth_setMining(bool const& _mining);
virtual std::string eth_solidity(std::string const& _code);
virtual std::string eth_stateAt(std::string const& _address, std::string const& _storage);
virtual Json::Value eth_storageAt(std::string const& _address);
virtual std::string eth_transact(Json::Value const& _json);
virtual Json::Value eth_transactionByHash(std::string const& _hash, int const& _i);
virtual Json::Value eth_transactionByNumber(int const& _number, int const& _i);

41
libweb3jsonrpc/abstractwebthreestubserver.h

@ -26,6 +26,7 @@ class AbstractWebThreeStubServer : public jsonrpc::AbstractServer<AbstractWebThr
this->bindAndAddMethod(new jsonrpc::Procedure("eth_number", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_INTEGER, NULL), &AbstractWebThreeStubServer::eth_numberI);
this->bindAndAddMethod(new jsonrpc::Procedure("eth_balanceAt", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_STRING, "param1",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::eth_balanceAtI);
this->bindAndAddMethod(new jsonrpc::Procedure("eth_stateAt", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_STRING, "param1",jsonrpc::JSON_STRING,"param2",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::eth_stateAtI);
this->bindAndAddMethod(new jsonrpc::Procedure("eth_storageAt", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_OBJECT, "param1",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::eth_storageAtI);
this->bindAndAddMethod(new jsonrpc::Procedure("eth_countAt", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_REAL, "param1",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::eth_countAtI);
this->bindAndAddMethod(new jsonrpc::Procedure("eth_codeAt", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_STRING, "param1",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::eth_codeAtI);
this->bindAndAddMethod(new jsonrpc::Procedure("eth_transact", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_STRING, "param1",jsonrpc::JSON_OBJECT, NULL), &AbstractWebThreeStubServer::eth_transactI);
@ -36,13 +37,16 @@ class AbstractWebThreeStubServer : public jsonrpc::AbstractServer<AbstractWebThr
this->bindAndAddMethod(new jsonrpc::Procedure("eth_transactionByNumber", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_OBJECT, "param1",jsonrpc::JSON_INTEGER,"param2",jsonrpc::JSON_INTEGER, NULL), &AbstractWebThreeStubServer::eth_transactionByNumberI);
this->bindAndAddMethod(new jsonrpc::Procedure("eth_uncleByHash", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_OBJECT, "param1",jsonrpc::JSON_STRING,"param2",jsonrpc::JSON_INTEGER, NULL), &AbstractWebThreeStubServer::eth_uncleByHashI);
this->bindAndAddMethod(new jsonrpc::Procedure("eth_uncleByNumber", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_OBJECT, "param1",jsonrpc::JSON_INTEGER,"param2",jsonrpc::JSON_INTEGER, NULL), &AbstractWebThreeStubServer::eth_uncleByNumberI);
this->bindAndAddMethod(new jsonrpc::Procedure("eth_compilers", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_ARRAY, NULL), &AbstractWebThreeStubServer::eth_compilersI);
this->bindAndAddMethod(new jsonrpc::Procedure("eth_lll", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_STRING, "param1",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::eth_lllI);
this->bindAndAddMethod(new jsonrpc::Procedure("eth_compile", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_STRING, "param1",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::eth_compileI);
this->bindAndAddMethod(new jsonrpc::Procedure("eth_solidity", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_STRING, "param1",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::eth_solidityI);
this->bindAndAddMethod(new jsonrpc::Procedure("eth_serpent", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_STRING, "param1",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::eth_serpentI);
this->bindAndAddMethod(new jsonrpc::Procedure("eth_newFilter", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_INTEGER, "param1",jsonrpc::JSON_OBJECT, NULL), &AbstractWebThreeStubServer::eth_newFilterI);
this->bindAndAddMethod(new jsonrpc::Procedure("eth_newFilterString", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_INTEGER, "param1",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::eth_newFilterStringI);
this->bindAndAddMethod(new jsonrpc::Procedure("eth_uninstallFilter", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_BOOLEAN, "param1",jsonrpc::JSON_INTEGER, NULL), &AbstractWebThreeStubServer::eth_uninstallFilterI);
this->bindAndAddMethod(new jsonrpc::Procedure("eth_changed", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_BOOLEAN, "param1",jsonrpc::JSON_INTEGER, NULL), &AbstractWebThreeStubServer::eth_changedI);
this->bindAndAddMethod(new jsonrpc::Procedure("eth_getMessages", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_ARRAY, "param1",jsonrpc::JSON_INTEGER, NULL), &AbstractWebThreeStubServer::eth_getMessagesI);
this->bindAndAddMethod(new jsonrpc::Procedure("eth_filterLogs", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_ARRAY, "param1",jsonrpc::JSON_INTEGER, NULL), &AbstractWebThreeStubServer::eth_filterLogsI);
this->bindAndAddMethod(new jsonrpc::Procedure("eth_logs", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_ARRAY, "param1",jsonrpc::JSON_OBJECT, NULL), &AbstractWebThreeStubServer::eth_logsI);
this->bindAndAddMethod(new jsonrpc::Procedure("db_put", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_BOOLEAN, "param1",jsonrpc::JSON_STRING,"param2",jsonrpc::JSON_STRING,"param3",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::db_putI);
this->bindAndAddMethod(new jsonrpc::Procedure("db_get", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_STRING, "param1",jsonrpc::JSON_STRING,"param2",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::db_getI);
this->bindAndAddMethod(new jsonrpc::Procedure("db_putString", jsonrpc::PARAMS_BY_POSITION, jsonrpc::JSON_BOOLEAN, "param1",jsonrpc::JSON_STRING,"param2",jsonrpc::JSON_STRING,"param3",jsonrpc::JSON_STRING, NULL), &AbstractWebThreeStubServer::db_putStringI);
@ -121,6 +125,10 @@ class AbstractWebThreeStubServer : public jsonrpc::AbstractServer<AbstractWebThr
{
response = this->eth_stateAt(request[0u].asString(), request[1u].asString());
}
inline virtual void eth_storageAtI(const Json::Value &request, Json::Value &response)
{
response = this->eth_storageAt(request[0u].asString());
}
inline virtual void eth_countAtI(const Json::Value &request, Json::Value &response)
{
response = this->eth_countAt(request[0u].asString());
@ -161,13 +169,22 @@ class AbstractWebThreeStubServer : public jsonrpc::AbstractServer<AbstractWebThr
{
response = this->eth_uncleByNumber(request[0u].asInt(), request[1u].asInt());
}
inline virtual void eth_compilersI(const Json::Value &request, Json::Value &response)
{
(void)request;
response = this->eth_compilers();
}
inline virtual void eth_lllI(const Json::Value &request, Json::Value &response)
{
response = this->eth_lll(request[0u].asString());
}
inline virtual void eth_compileI(const Json::Value &request, Json::Value &response)
inline virtual void eth_solidityI(const Json::Value &request, Json::Value &response)
{
response = this->eth_compile(request[0u].asString());
response = this->eth_solidity(request[0u].asString());
}
inline virtual void eth_serpentI(const Json::Value &request, Json::Value &response)
{
response = this->eth_serpent(request[0u].asString());
}
inline virtual void eth_newFilterI(const Json::Value &request, Json::Value &response)
{
@ -185,9 +202,13 @@ class AbstractWebThreeStubServer : public jsonrpc::AbstractServer<AbstractWebThr
{
response = this->eth_changed(request[0u].asInt());
}
inline virtual void eth_getMessagesI(const Json::Value &request, Json::Value &response)
inline virtual void eth_filterLogsI(const Json::Value &request, Json::Value &response)
{
response = this->eth_filterLogs(request[0u].asInt());
}
inline virtual void eth_logsI(const Json::Value &request, Json::Value &response)
{
response = this->eth_getMessages(request[0u].asInt());
response = this->eth_logs(request[0u]);
}
inline virtual void db_putI(const Json::Value &request, Json::Value &response)
{
@ -252,6 +273,7 @@ class AbstractWebThreeStubServer : public jsonrpc::AbstractServer<AbstractWebThr
virtual int eth_number() = 0;
virtual std::string eth_balanceAt(const std::string& param1) = 0;
virtual std::string eth_stateAt(const std::string& param1, const std::string& param2) = 0;
virtual Json::Value eth_storageAt(const std::string& param1) = 0;
virtual double eth_countAt(const std::string& param1) = 0;
virtual std::string eth_codeAt(const std::string& param1) = 0;
virtual std::string eth_transact(const Json::Value& param1) = 0;
@ -262,13 +284,16 @@ class AbstractWebThreeStubServer : public jsonrpc::AbstractServer<AbstractWebThr
virtual Json::Value eth_transactionByNumber(const int& param1, const int& param2) = 0;
virtual Json::Value eth_uncleByHash(const std::string& param1, const int& param2) = 0;
virtual Json::Value eth_uncleByNumber(const int& param1, const int& param2) = 0;
virtual Json::Value eth_compilers() = 0;
virtual std::string eth_lll(const std::string& param1) = 0;
virtual std::string eth_compile(const std::string& param1) = 0;
virtual std::string eth_solidity(const std::string& param1) = 0;
virtual std::string eth_serpent(const std::string& param1) = 0;
virtual int eth_newFilter(const Json::Value& param1) = 0;
virtual int eth_newFilterString(const std::string& param1) = 0;
virtual bool eth_uninstallFilter(const int& param1) = 0;
virtual bool eth_changed(const int& param1) = 0;
virtual Json::Value eth_getMessages(const int& param1) = 0;
virtual Json::Value eth_filterLogs(const int& param1) = 0;
virtual Json::Value eth_logs(const Json::Value& param1) = 0;
virtual bool db_put(const std::string& param1, const std::string& param2, const std::string& param3) = 0;
virtual std::string db_get(const std::string& param1, const std::string& param2) = 0;
virtual bool db_putString(const std::string& param1, const std::string& param2, const std::string& param3) = 0;

9
libweb3jsonrpc/spec.json

@ -14,6 +14,7 @@
{ "name": "eth_balanceAt", "params": [""], "order": [], "returns" : ""},
{ "name": "eth_stateAt", "params": ["", ""], "order": [], "returns": ""},
{ "name": "eth_storageAt", "params": [""], "order": [], "returns": {}},
{ "name": "eth_countAt", "params": [""], "order": [], "returns" : 0.0},
{ "name": "eth_codeAt", "params": [""], "order": [], "returns": ""},
@ -27,14 +28,18 @@
{ "name": "eth_uncleByHash", "params": ["", 0], "order": [], "returns": {}},
{ "name": "eth_uncleByNumber", "params": [0, 0], "order": [], "returns": {}},
{ "name": "eth_compilers", "params": [], "order": [], "returns": []},
{ "name": "eth_lll", "params": [""], "order": [], "returns": ""},
{ "name": "eth_compile", "params": [""], "order": [], "returns": ""},
{ "name": "eth_solidity", "params": [""], "order": [], "returns": ""},
{ "name": "eth_serpent", "params": [""], "order": [], "returns": ""},
{ "name": "eth_newFilter", "params": [{}], "order": [], "returns": 0},
{ "name": "eth_newFilterString", "params": [""], "order": [], "returns": 0},
{ "name": "eth_uninstallFilter", "params": [0], "order": [], "returns": true},
{ "name": "eth_changed", "params": [0], "order": [], "returns": false},
{ "name": "eth_getMessages", "params": [0], "order": [], "returns": []},
{ "name": "eth_filterLogs", "params": [0], "order": [], "returns": []},
{ "name": "eth_logs", "params": [{}], "order": [], "returns": []},
{ "name": "db_put", "params": ["", "", ""], "order": [], "returns": true},
{ "name": "db_get", "params": ["", ""], "order": [], "returns": ""},

2
stdserv.js

@ -17,7 +17,7 @@ config.then(function() {
web3.eth.accounts.then(function(accounts)
{
var funded = send(accounts[0], '100000000000000000000', accounts[1]);
funded.then(function(){ env.note("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); regName(accounts[1], 'Gav Would'); env.note("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); approve(accounts[1], exchange); });
funded.then(function(){ regName(accounts[1], 'Gav Would'); approve(accounts[1], exchange); });
regName(accounts[0], 'Gav');
approve(accounts[0], exchange).then(function(){ offer(accounts[0], coin, '5000', '0', '5000000000000000000'); });

66
test/jsonrpc.cpp

@ -239,6 +239,72 @@ BOOST_AUTO_TEST_CASE(jsonrpc_transact)
BOOST_CHECK_EQUAL(txAmount, balance2);
}
BOOST_AUTO_TEST_CASE(simple_contract)
{
cnote << "Testing jsonrpc contract...";
KeyPair kp = KeyPair::create();
web3->ethereum()->setAddress(kp.address());
jsonrpcServer->setAccounts({kp});
dev::eth::mine(*(web3->ethereum()), 1);
char const* sourceCode = "contract test {\n"
" function f(uint a) returns(uint d) { return a * 7; }\n"
"}\n";
string compiled = jsonrpcClient->eth_solidity(sourceCode);
Json::Value create;
create["code"] = compiled;
string contractAddress = jsonrpcClient->eth_transact(create);
dev::eth::mine(*(web3->ethereum()), 1);
Json::Value call;
call["to"] = contractAddress;
call["data"] = "0x00000000000000000000000000000000000000000000000000000000000000001";
string result = jsonrpcClient->eth_call(call);
BOOST_CHECK_EQUAL(result, "0x0000000000000000000000000000000000000000000000000000000000000007");
}
BOOST_AUTO_TEST_CASE(contract_storage)
{
cnote << "Testing jsonrpc contract storage...";
KeyPair kp = KeyPair::create();
web3->ethereum()->setAddress(kp.address());
jsonrpcServer->setAccounts({kp});
dev::eth::mine(*(web3->ethereum()), 1);
char const* sourceCode = R"(
contract test {
uint hello;
function writeHello(uint value) returns(bool d){
hello = value;
return true;
}
}
)";
string compiled = jsonrpcClient->eth_solidity(sourceCode);
Json::Value create;
create["code"] = compiled;
string contractAddress = jsonrpcClient->eth_transact(create);
dev::eth::mine(*(web3->ethereum()), 1);
Json::Value transact;
transact["to"] = contractAddress;
transact["data"] = "0x00000000000000000000000000000000000000000000000000000000000000003";
jsonrpcClient->eth_transact(transact);
dev::eth::mine(*(web3->ethereum()), 1);
Json::Value storage = jsonrpcClient->eth_storageAt(contractAddress);
BOOST_CHECK_EQUAL(storage.getMemberNames().size(), 1);
for (auto name: storage.getMemberNames())
BOOST_CHECK_EQUAL(storage[name].asString(), "0x03");
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()

48
test/webthreestubclient.h

@ -153,6 +153,16 @@ class WebThreeStubClient : public jsonrpc::Client
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value eth_storageAt(const std::string& param1) throw (jsonrpc::JsonRpcException)
{
Json::Value p;
p.append(param1);
Json::Value result = this->CallMethod("eth_storageAt",p);
if (result.isObject())
return result;
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
double eth_countAt(const std::string& param1) throw (jsonrpc::JsonRpcException)
{
Json::Value p;
@ -257,6 +267,16 @@ class WebThreeStubClient : public jsonrpc::Client
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value eth_compilers() throw (jsonrpc::JsonRpcException)
{
Json::Value p;
p = Json::nullValue;
Json::Value result = this->CallMethod("eth_compilers",p);
if (result.isArray())
return result;
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
std::string eth_lll(const std::string& param1) throw (jsonrpc::JsonRpcException)
{
Json::Value p;
@ -267,11 +287,21 @@ class WebThreeStubClient : public jsonrpc::Client
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
std::string eth_compile(const std::string& param1) throw (jsonrpc::JsonRpcException)
std::string eth_solidity(const std::string& param1) throw (jsonrpc::JsonRpcException)
{
Json::Value p;
p.append(param1);
Json::Value result = this->CallMethod("eth_compile",p);
Json::Value result = this->CallMethod("eth_solidity",p);
if (result.isString())
return result.asString();
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
std::string eth_serpent(const std::string& param1) throw (jsonrpc::JsonRpcException)
{
Json::Value p;
p.append(param1);
Json::Value result = this->CallMethod("eth_serpent",p);
if (result.isString())
return result.asString();
else
@ -317,11 +347,21 @@ class WebThreeStubClient : public jsonrpc::Client
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value eth_getMessages(const int& param1) throw (jsonrpc::JsonRpcException)
Json::Value eth_filterLogs(const int& param1) throw (jsonrpc::JsonRpcException)
{
Json::Value p;
p.append(param1);
Json::Value result = this->CallMethod("eth_filterLogs",p);
if (result.isArray())
return result;
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value eth_logs(const Json::Value& param1) throw (jsonrpc::JsonRpcException)
{
Json::Value p;
p.append(param1);
Json::Value result = this->CallMethod("eth_getMessages",p);
Json::Value result = this->CallMethod("eth_logs",p);
if (result.isArray())
return result;
else

17
third/MainWin.cpp

@ -182,7 +182,7 @@ void Main::onKeysChanged()
installBalancesWatch();
}
unsigned Main::installWatch(dev::eth::MessageFilter const& _tf, std::function<void()> const& _f)
unsigned Main::installWatch(dev::eth::LogFilter const& _tf, std::function<void()> const& _f)
{
auto ret = ethereum()->installWatch(_tf);
m_handlers[ret] = _f;
@ -198,37 +198,34 @@ unsigned Main::installWatch(dev::h256 _tf, std::function<void()> const& _f)
void Main::installWatches()
{
installWatch(dev::eth::MessageFilter().altered(c_config, 0), [=](){ installNameRegWatch(); });
installWatch(dev::eth::MessageFilter().altered(c_config, 1), [=](){ installCurrenciesWatch(); });
installWatch(dev::eth::LogFilter().topic((u256)(u160)c_config).topic((u256)0), [=](){ installNameRegWatch(); });
installWatch(dev::eth::LogFilter().topic((u256)(u160)c_config).topic((u256)1), [=](){ installCurrenciesWatch(); });
installWatch(dev::eth::ChainChangedFilter, [=](){ onNewBlock(); });
}
void Main::installNameRegWatch()
{
ethereum()->uninstallWatch(m_nameRegFilter);
m_nameRegFilter = installWatch(dev::eth::MessageFilter().altered((u160)ethereum()->stateAt(c_config, 0)), [=](){ onNameRegChange(); });
m_nameRegFilter = installWatch(dev::eth::LogFilter().topic(ethereum()->stateAt(c_config, 0)), [=](){ onNameRegChange(); });
}
void Main::installCurrenciesWatch()
{
ethereum()->uninstallWatch(m_currenciesFilter);
m_currenciesFilter = installWatch(dev::eth::MessageFilter().altered((u160)ethereum()->stateAt(c_config, 1)), [=](){ onCurrenciesChange(); });
m_currenciesFilter = installWatch(dev::eth::LogFilter().topic(ethereum()->stateAt(c_config, 1)), [=](){ onCurrenciesChange(); });
}
void Main::installBalancesWatch()
{
dev::eth::MessageFilter tf;
dev::eth::LogFilter tf;
vector<Address> altCoins;
Address coinsAddr = right160(ethereum()->stateAt(c_config, 1));
for (unsigned i = 0; i < ethereum()->stateAt(coinsAddr, 0); ++i)
altCoins.push_back(right160(ethereum()->stateAt(coinsAddr, i + 1)));
for (auto i: m_myKeys)
{
tf.altered(i.address());
for (auto c: altCoins)
tf.altered(c, (u160)i.address());
}
tf.address(c).topic((u256)(u160)i.address());
ethereum()->uninstallWatch(m_balancesFilter);
m_balancesFilter = installWatch(tf, [=](){ onBalancesChange(); });

4
third/MainWin.h

@ -40,7 +40,7 @@ namespace dev { class WebThreeDirect;
namespace eth {
class Client;
class State;
class MessageFilter;
class LogFilter;
}
namespace shh {
class WhisperHost;
@ -95,7 +95,7 @@ private:
void readSettings(bool _skipGeometry = false);
void writeSettings();
unsigned installWatch(dev::eth::MessageFilter const& _tf, std::function<void()> const& _f);
unsigned installWatch(dev::eth::LogFilter const& _tf, std::function<void()> const& _f);
unsigned installWatch(dev::h256 _tf, std::function<void()> const& _f);
void onNewBlock();

Loading…
Cancel
Save