This commit is contained in:
Alexandre Van de Sande 2015-02-10 14:44:07 +00:00
commit 69b3a401d1
145 changed files with 3217 additions and 10340 deletions

View file

@ -1,6 +1,6 @@
language: go language: go
go: go:
- 1.4.1 - tip
before_install: before_install:
- sudo add-apt-repository ppa:beineri/opt-qt54 -y - sudo add-apt-repository ppa:beineri/opt-qt54 -y
- sudo apt-get update -qq - sudo apt-get update -qq
@ -12,7 +12,7 @@ install:
- if ! go get code.google.com/p/go.tools/cmd/cover; then go get golang.org/x/tools/cmd/cover; fi - if ! go get code.google.com/p/go.tools/cmd/cover; then go get golang.org/x/tools/cmd/cover; fi
- go get github.com/mattn/goveralls - go get github.com/mattn/goveralls
- go get -d github.com/obscuren/qml && cd $HOME/gopath/src/github.com/obscuren/qml && git checkout v1 && cd $TRAVIS_BUILD_DIR - go get -d github.com/obscuren/qml && cd $HOME/gopath/src/github.com/obscuren/qml && git checkout v1 && cd $TRAVIS_BUILD_DIR
- ETH_DEPS=$(go list -f '{{.Imports}} {{.TestImports}} {{.XTestImports}}' github.com/ethereum/go-ethereum/... | sed -e 's/\[//g' | sed -e 's/\]//g' | sed -e 's/C //g'); if [ "$ETH_DEPS" ]; then go get -d $ETH_DEPS; fi - ETH_DEPS=$(go list -f '{{.Imports}} {{.TestImports}} {{.XTestImports}}' github.com/ethereum/go-ethereum/... | sed -e 's/\[//g' | sed -e 's/\]//g' | sed -e 's/C //g'); if [ "$ETH_DEPS" ]; then go get $ETH_DEPS; fi
before_script: before_script:
- gofmt -l -w . - gofmt -l -w .
- goimports -l -w . - goimports -l -w .
@ -20,7 +20,7 @@ before_script:
# - go vet ./... # - go vet ./...
# - go test -race ./... # - go test -race ./...
script: script:
- ./gocoverage.sh && if [ "$COVERALLS_TOKEN" ]; then goveralls -coverprofile=profile.cov -service=travis-ci -repotoken $COVERALLS_TOKEN; fi - ./gocoverage.sh
env: env:
global: global:
- PKG_CONFIG_PATH=/opt/qt54/lib/pkgconfig - PKG_CONFIG_PATH=/opt/qt54/lib/pkgconfig

View file

@ -1,18 +1,19 @@
## Ethereum Go
Ethereum Go Client © 2014 Jeffrey Wilcke.
| Linux | OSX | Windows
----------|---------|-----|--------
develop | [![Build+Status](http://build.ethdev.com/buildstatusimage?builder=Linux%20Go%20develop%20branch)](http://build.ethdev.com/builders/Linux%20Go%20develop%20branch/builds/-1) | [![Build+Status](http://build.ethdev.com/buildstatusimage?builder=Linux%20Go%20develop%20branch)](http://build.ethdev.com/builders/OSX%20Go%20develop%20branch/builds/-1) | N/A
master | [![Build+Status](http://build.ethdev.com/buildstatusimage?builder=Linux%20Go%20master%20branch)](http://build.ethdev.com/builders/Linux%20Go%20master%20branch/builds/-1) | [![Build+Status](http://build.ethdev.com/buildstatusimage?builder=OSX%20Go%20master%20branch)](http://build.ethdev.com/builders/OSX%20Go%20master%20branch/builds/-1) | N/A
[![Bugs](https://badge.waffle.io/ethereum/go-ethereum.png?label=bug&title=Bugs)](https://waffle.io/ethereum/go-ethereum) [![Bugs](https://badge.waffle.io/ethereum/go-ethereum.png?label=bug&title=Bugs)](https://waffle.io/ethereum/go-ethereum)
[![Stories in Ready](https://badge.waffle.io/ethereum/go-ethereum.png?label=ready&title=Ready)](https://waffle.io/ethereum/go-ethereum) [![Stories in Ready](https://badge.waffle.io/ethereum/go-ethereum.png?label=ready&title=Ready)](https://waffle.io/ethereum/go-ethereum)
[![Stories in Progress](https://badge.waffle.io/ethereum/go-ethereum.svg?label=in%20progress&title=In Progress)](http://waffle.io/ethereum/go-ethereum) [![Stories in Progress](https://badge.waffle.io/ethereum/go-ethereum.svg?label=in%20progress&title=In Progress)](http://waffle.io/ethereum/go-ethereum)
[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/ethereum/go-ethereum?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/ethereum/go-ethereum?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
Ethereum PoC-8
========
* [![Build Status](http://build.ethdev.com/buildstatusimage?builder=Linux%20Go%20master%20branch)](http://build.ethdev.com:8010/builders/Linux%20Go%20master%20branch/builds/-1) master
* [![Build Status](http://build.ethdev.com/buildstatusimage?builder=Linux%20Go%20develop%20branch)](http://build.ethdev.com:8010/builders/Linux%20Go%20develop%20branch/builds/-1) develop
* [![Travis-ci](https://api.travis-ci.org/ethereum/go-ethereum.svg)](https://travis-ci.org/ethereum/go-ethereum) travis-ci
* [![Coverage Status](https://coveralls.io/repos/ethereum/go-ethereum/badge.png?branch=develop)](https://coveralls.io/r/ethereum/go-ethereum?branch=develop)
Ethereum Go Client © 2014 Jeffrey Wilcke.
Build Build
===== =====

View file

@ -49,7 +49,7 @@ var (
AddPeer string AddPeer string
MaxPeer int MaxPeer int
GenAddr bool GenAddr bool
SeedNode string UseSeed bool
SecretFile string SecretFile string
ExportDir string ExportDir string
NonInteractive bool NonInteractive bool
@ -96,12 +96,12 @@ func Init() {
flag.StringVar(&NatType, "nat", "", "NAT support (UPNP|PMP) (none)") flag.StringVar(&NatType, "nat", "", "NAT support (UPNP|PMP) (none)")
flag.StringVar(&PMPGateway, "pmp", "", "Gateway IP for PMP") flag.StringVar(&PMPGateway, "pmp", "", "Gateway IP for PMP")
flag.IntVar(&MaxPeer, "maxpeer", 30, "maximum desired peers") flag.IntVar(&MaxPeer, "maxpeer", 30, "maximum desired peers")
flag.IntVar(&RpcPort, "rpcport", 8545, "port to start json-rpc server on") flag.IntVar(&RpcPort, "rpcport", 8080, "port to start json-rpc server on")
flag.IntVar(&WsPort, "wsport", 40404, "port to start websocket rpc server on") flag.IntVar(&WsPort, "wsport", 40404, "port to start websocket rpc server on")
flag.BoolVar(&StartRpc, "rpc", false, "start rpc server") flag.BoolVar(&StartRpc, "rpc", false, "start rpc server")
flag.BoolVar(&StartWebSockets, "ws", false, "start websocket server") flag.BoolVar(&StartWebSockets, "ws", false, "start websocket server")
flag.BoolVar(&NonInteractive, "y", false, "non-interactive mode (say yes to confirmations)") flag.BoolVar(&NonInteractive, "y", false, "non-interactive mode (say yes to confirmations)")
flag.StringVar(&SeedNode, "seednode", "poc-8.ethdev.com:30303", "ip:port of seed node to connect to. Set to blank for skip") flag.BoolVar(&UseSeed, "seed", true, "seed peers")
flag.BoolVar(&SHH, "shh", true, "whisper protocol (on)") flag.BoolVar(&SHH, "shh", true, "whisper protocol (on)")
flag.BoolVar(&Dial, "dial", true, "dial out connections (on)") flag.BoolVar(&Dial, "dial", true, "dial out connections (on)")
flag.BoolVar(&GenAddr, "genaddr", false, "create a new priv/pub key") flag.BoolVar(&GenAddr, "genaddr", false, "create a new priv/pub key")

View file

@ -134,7 +134,7 @@ func main() {
utils.StartWebSockets(ethereum, WsPort) utils.StartWebSockets(ethereum, WsPort)
} }
utils.StartEthereum(ethereum, SeedNode) utils.StartEthereum(ethereum, UseSeed)
if StartJsConsole { if StartJsConsole {
InitJsConsole(ethereum) InitJsConsole(ethereum)

View file

@ -128,7 +128,6 @@ func (self *VMEnv) Difficulty() *big.Int { return ethutil.Big1 }
func (self *VMEnv) BlockHash() []byte { return make([]byte, 32) } func (self *VMEnv) BlockHash() []byte { return make([]byte, 32) }
func (self *VMEnv) Value() *big.Int { return self.value } func (self *VMEnv) Value() *big.Int { return self.value }
func (self *VMEnv) GasLimit() *big.Int { return big.NewInt(1000000000) } func (self *VMEnv) GasLimit() *big.Int { return big.NewInt(1000000000) }
func (self *VMEnv) VmType() vm.Type { return vm.StdVmTy }
func (self *VMEnv) Depth() int { return 0 } func (self *VMEnv) Depth() int { return 0 }
func (self *VMEnv) SetDepth(i int) { self.depth = i } func (self *VMEnv) SetDepth(i int) { self.depth = i }
func (self *VMEnv) GetHash(n uint64) []byte { func (self *VMEnv) GetHash(n uint64) []byte {

Binary file not shown.

After

Width:  |  Height:  |  Size: 663 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

View file

@ -21,7 +21,7 @@
}]; }];
var address = web3.eth.transact({ var address = web3.eth.transact({
data: "0x603880600c6000396000f3006001600060e060020a600035048063c6888fa114601857005b6021600435602b565b8060005260206000f35b600081600702905091905056", data: "0x603880600c6000396000f3006001600060e060020a600035048063c6888fa114601857005b6021600435602b565b8060005260206000f35b600081600702905091905056",
gasPrice: "1000000000000000", gasprice: "1000000000000000",
gas: "10000", gas: "10000",
}); });
var contract = web3.eth.contract(address, desc); var contract = web3.eth.contract(address, desc);

View file

@ -30,10 +30,6 @@
<td id="accounts"></td> <td id="accounts"></td>
</tr> </tr>
<tr>
<td>Balance</td>
<td id="balance"></td>
<tr> <tr>
<td>Gas price</td> <td>Gas price</td>
<td id="gas_price"></td> <td id="gas_price"></td>
@ -67,7 +63,6 @@
document.querySelector("#peer_count").innerHTML = eth.peerCount; document.querySelector("#peer_count").innerHTML = eth.peerCount;
document.querySelector("#default_block").innerHTML = eth.defaultBlock; document.querySelector("#default_block").innerHTML = eth.defaultBlock;
document.querySelector("#accounts").innerHTML = eth.accounts; document.querySelector("#accounts").innerHTML = eth.accounts;
document.querySelector("#balance").innerHTML = web3.toEth(eth.balanceAt(eth.accounts[0]));
document.querySelector("#gas_price").innerHTML = eth.gasPrice; document.querySelector("#gas_price").innerHTML = eth.gasPrice;
document.querySelector("#mining").innerHTML = eth.mining; document.querySelector("#mining").innerHTML = eth.mining;
document.querySelector("#listening").innerHTML = eth.listening; document.querySelector("#listening").innerHTML = eth.listening;

View file

@ -10,7 +10,6 @@
<h1>Whisper test</h1> <h1>Whisper test</h1>
<button onclick="test()">Send</button> <button onclick="test()">Send</button>
<button onclick="test2()">Private send</button>
<table width="100%" id="table"> <table width="100%" id="table">
<tr> <tr>
@ -45,19 +44,10 @@
document.querySelector("#table").innerHTML += "<tr><td colspan='2'>"+JSON.stringify(message)+"</td></tr>"; document.querySelector("#table").innerHTML += "<tr><td colspan='2'>"+JSON.stringify(message)+"</td></tr>";
}); });
var selfWatch = shh.watch({to: id, topics: ["test"]})
selfWatch.arrived(function(message) {
document.querySelector("#table").innerHTML += "<tr><td>To me</td><td>"+JSON.stringify(message)+"</td></tr>";
});
function test() { function test() {
shh.post({topics: ["test"], payload: web3.fromAscii("test it")}); shh.post({topics: ["test"], payload: web3.fromAscii("test it")});
count(); count();
}
function test2() {
shh.post({to: id, topics: ["test"], payload: web3.fromAscii("Private")});
count();
} }
function count() { function count() {

View file

@ -1,7 +1,7 @@
{ {
"name": "ethereum.js", "name": "ethereum.js",
"namespace": "ethereum", "namespace": "ethereum",
"version": "0.0.13", "version": "0.0.10",
"description": "Ethereum Compatible JavaScript API", "description": "Ethereum Compatible JavaScript API",
"main": ["./dist/ethereum.js", "./dist/ethereum.min.js"], "main": ["./dist/ethereum.js", "./dist/ethereum.min.js"],
"dependencies": { "dependencies": {

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -17,11 +17,7 @@
var originalBalance = web3.toDecimal(balance); var originalBalance = web3.toDecimal(balance);
document.getElementById('original').innerText = 'original balance: ' + originalBalance + ' watching...'; document.getElementById('original').innerText = 'original balance: ' + originalBalance + ' watching...';
<<<<<<< HEAD:cmd/mist/assets/ext/ethereum.js/example/balance.html
var filter = web3.eth.watch({address: coinbase}).changed(function() { var filter = web3.eth.watch({address: coinbase}).changed(function() {
=======
web3.eth.watch('pending').changed(function() {
>>>>>>> 859a1999cb204d2c6fcb08d6569c738c5af5cd86:example/balance.html
balance = web3.eth.balanceAt(coinbase) balance = web3.eth.balanceAt(coinbase)
var currentBalance = web3.toDecimal(balance); var currentBalance = web3.toDecimal(balance);
document.getElementById("current").innerText = 'current: ' + currentBalance; document.getElementById("current").innerText = 'current: ' + currentBalance;

View file

@ -20,7 +20,6 @@
// contract description, this will be autogenerated somehow // contract description, this will be autogenerated somehow
var desc = [{ var desc = [{
"name": "multiply(uint256)", "name": "multiply(uint256)",
"type": "function",
"inputs": [ "inputs": [
{ {
"name": "a", "name": "a",

View file

@ -1,76 +0,0 @@
<!doctype>
<html>
<head>
<script type="text/javascript" src="js/bignumber.js/bignumber.min.js"></script>
<script type="text/javascript" src="../dist/ethereum.js"></script>
<script type="text/javascript">
var web3 = require('web3');
web3.setProvider(new web3.providers.HttpSyncProvider());
// solidity source code
var source = "" +
"contract test {\n" +
" function multiply(uint[] a) returns(uint d) {\n" +
" return a[0] + a[1];\n" +
" }\n" +
"}\n";
// contract description, this will be autogenerated somehow
var desc = [{
"name": "multiply(uint256[])",
"type": "function",
"inputs": [
{
"name": "a",
"type": "uint256[]"
}
],
"outputs": [
{
"name": "d",
"type": "uint256"
}
]
}];
var contract;
function createExampleContract() {
// hide create button
document.getElementById('create').style.visibility = 'hidden';
document.getElementById('source').innerText = source;
// create contract
var address = web3.eth.transact({code: web3.eth.solidity(source)});
contract = web3.eth.contract(address, desc);
document.getElementById('call').style.visibility = 'visible';
}
function callExampleContract() {
// this should be generated by ethereum
var param = parseInt(document.getElementById('value').value);
var param2 = parseInt(document.getElementById('value2').value);
// call the contract
var res = contract.call().multiply([param, param2]);
document.getElementById('result').innerText = res.toString(10);
}
</script>
</head>
<body>
<h1>contract</h1>
<div id="source"></div>
<div id='create'>
<button type="button" onClick="createExampleContract();">create example contract</button>
</div>
<div id='call' style='visibility: hidden;'>
<input type="number" id="value" onkeyup='callExampleContract()'></input>
<input type="number" id="value2" onkeyup='callExampleContract()'></input>
</div>
<div id="result"></div>
</body>
</html>

View file

@ -1,120 +0,0 @@
<!doctype>
<html>
<head>
<script type="text/javascript" src="js/bignumber.js/bignumber.min.js"></script>
<script type="text/javascript" src="../dist/ethereum.js"></script>
<script type="text/javascript">
var web3 = require('web3');
web3.setProvider(new web3.providers.HttpSyncProvider('http://localhost:8080'));
var desc = [{
"type":"event",
"inputs": [{"name":"a","type":"uint256","indexed":true},{"name":"b","type":"hash256","indexed":false}],
"name":"Event"
}, {
"type":"event",
"inputs": [{"name":"a","type":"uint256","indexed":true},{"name":"b","type":"hash256","indexed":false}],
"name":"Event2"
}, {
"type":"function",
"inputs": [{"name":"a","type":"uint256"}],
"name":"foo",
"outputs": []
}];
var address = '0x01';
var contract = web3.eth.contract(address, desc);
function test1() {
// "{"topic":["0x83c9849c","0xc4d76332"],"address":"0x01"}"
web3.eth.watch(contract).changed(function (res) {
});
};
function test2() {
// "{"topic":["0x83c9849c"],"address":"0x01"}"
web3.eth.watch(contract.Event).changed(function (res) {
});
};
function test3() {
// "{"topic":["0x83c9849c"],"address":"0x01"}"
contract.Event().changed(function (res) {
});
};
function test4() {
// "{"topic":["0x83c9849c","0000000000000000000000000000000000000000000000000000000000000045"],"address":"0x01"}"
contract.Event({a: 69}).changed(function (res) {
});
};
function test5() {
// "{"topic":["0x83c9849c",["0000000000000000000000000000000000000000000000000000000000000045","000000000000000000000000000000000000000000000000000000000000002a"]],"address":"0x01"}"
contract.Event({a: [69, 42]}).changed(function (res) {
});
};
function test6() {
// "{"topic":["0x83c9849c","000000000000000000000000000000000000000000000000000000000000001e"],"max":100,"address":"0x01"}"
contract.Event({a: 30}, {max: 100}).changed(function (res) {
});
};
function test7() {
// "{"topic":["0x83c9849c","000000000000000000000000000000000000000000000000000000000000001e"],"address":"0x01"}"
web3.eth.watch(contract.Event, {a: 30}).changed(function (res) {
});
};
function test8() {
// "{"topic":["0x83c9849c","000000000000000000000000000000000000000000000000000000000000001e"],"max":100,"address":"0x01"}"
web3.eth.watch(contract.Event, {a: 30}, {max: 100}).changed(function (res) {
});
};
// not valid
// function testX() {
// web3.eth.watch([contract.Event, contract.Event2]).changed(function (res) {
// });
// };
</script>
</head>
<body>
<div>
<button type="button" onClick="test1();">test1</button>
</div>
<div>
<button type="button" onClick="test2();">test2</button>
</div>
<div>
<button type="button" onClick="test3();">test3</button>
</div>
<div>
<button type="button" onClick="test4();">test4</button>
</div>
<div>
<button type="button" onClick="test5();">test5</button>
</div>
<div>
<button type="button" onClick="test6();">test6</button>
</div>
<div>
<button type="button" onClick="test7();">test7</button>
</div>
<div>
<button type="button" onClick="test8();">test8</button>
</div>
</body>
</html>

View file

@ -1,66 +0,0 @@
<!doctype>
<html>
<head>
<script type="text/javascript" src="js/bignumber.js/bignumber.min.js"></script>
<script type="text/javascript" src="../dist/ethereum.js"></script>
<script type="text/javascript">
var web3 = require('web3');
web3.setProvider(new web3.providers.HttpSyncProvider('http://localhost:8080'));
var source = "" +
"contract Contract { " +
" event Incremented(bool indexed odd, uint x); " +
" function Contract() { " +
" x = 69; " +
" } " +
" function inc() { " +
" ++x; " +
" Incremented(x % 2 == 1, x); " +
" } " +
" uint x; " +
"}";
var desc = [{
"type":"event",
"name":"Incremented",
"inputs": [{"name":"odd","type":"bool","indexed":true},{"name":"x","type":"uint","indexed":false}],
}, {
"type":"function",
"name":"inc",
"inputs": [],
"outputs": []
}];
var address;
var contract;
var update = function (x) {
document.getElementById('result').innerText = JSON.stringify(x);
};
var createContract = function () {
address = web3.eth.transact({code: web3.eth.solidity(source)});
contract = web3.eth.contract(address, desc);
contract.Incremented({odd: true}).changed(update);
};
var callContract = function () {
contract.call().inc();
};
</script>
</head>
<body>
<div>
<button type="button" onClick="createContract();">create contract</button>
</div>
<div>
<button type="button" onClick="callContract();">test1</button>
</div>
<div id="result">
</div>
</body>
</html>

View file

@ -21,7 +21,6 @@
// contract description, this will be autogenerated somehow // contract description, this will be autogenerated somehow
var desc = [{ var desc = [{
"name": "multiply(uint256)", "name": "multiply(uint256)",
"type": "function",
"inputs": [ "inputs": [
{ {
"name": "a", "name": "a",

View file

@ -21,57 +21,175 @@
* @date 2014 * @date 2014
*/ */
var web3 = require('./web3'); // TODO: is these line is supposed to be here?
var utils = require('./utils'); if (process.env.NODE_ENV !== 'build') {
var types = require('./types'); var BigNumber = require('bignumber.js'); // jshint ignore:line
var c = require('./const'); }
var f = require('./formatters');
var displayTypeError = function (type) { var web3 = require('./web3'); // jshint ignore:line
console.error('parser does not support type: ' + type);
BigNumber.config({ ROUNDING_MODE: BigNumber.ROUND_DOWN });
var ETH_PADDING = 32;
/// method signature length in bytes
var ETH_METHOD_SIGNATURE_LENGTH = 4;
/// Finds first index of array element matching pattern
/// @param array
/// @param callback pattern
/// @returns index of element
var findIndex = function (array, callback) {
var end = false;
var i = 0;
for (; i < array.length && !end; i++) {
end = callback(array[i]);
}
return end ? i - 1 : -1;
};
/// @returns a function that is used as a pattern for 'findIndex'
var findMethodIndex = function (json, methodName) {
return findIndex(json, function (method) {
return method.name === methodName;
});
};
/// @returns method with given method name
var getMethodWithName = function (json, methodName) {
var index = findMethodIndex(json, methodName);
if (index === -1) {
console.error('method ' + methodName + ' not found in the abi');
return undefined;
}
return json[index];
};
/// @param string string to be padded
/// @param number of characters that result string should have
/// @param sign, by default 0
/// @returns right aligned string
var padLeft = function (string, chars, sign) {
return new Array(chars - string.length + 1).join(sign ? sign : "0") + string;
};
/// @param expected type prefix (string)
/// @returns function which checks if type has matching prefix. if yes, returns true, otherwise false
var prefixedType = function (prefix) {
return function (type) {
return type.indexOf(prefix) === 0;
};
};
/// @param expected type name (string)
/// @returns function which checks if type is matching expected one. if yes, returns true, otherwise false
var namedType = function (name) {
return function (type) {
return name === type;
};
}; };
/// This method should be called if we want to check if givent type is an array type
/// @returns true if it is, otherwise false
var arrayType = function (type) { var arrayType = function (type) {
return type.slice(-2) === '[]'; return type.slice(-2) === '[]';
}; };
/// Formats input value to byte representation of int
/// If value is negative, return it's two's complement
/// If the value is floating point, round it down
/// @returns right-aligned byte representation of int
var formatInputInt = function (value) {
var padding = ETH_PADDING * 2;
if (value instanceof BigNumber || typeof value === 'number') {
if (typeof value === 'number')
value = new BigNumber(value);
value = value.round();
if (value.lessThan(0))
value = new BigNumber("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16).plus(value).plus(1);
value = value.toString(16);
}
else if (value.indexOf('0x') === 0)
value = value.substr(2);
else if (typeof value === 'string')
value = formatInputInt(new BigNumber(value));
else
value = (+value).toString(16);
return padLeft(value, padding);
};
/// Formats input value to byte representation of string
/// @returns left-algined byte representation of string
var formatInputString = function (value) {
return web3.fromAscii(value, ETH_PADDING).substr(2);
};
/// Formats input value to byte representation of bool
/// @returns right-aligned byte representation bool
var formatInputBool = function (value) {
return '000000000000000000000000000000000000000000000000000000000000000' + (value ? '1' : '0');
};
/// Formats input value to byte representation of real
/// Values are multiplied by 2^m and encoded as integers
/// @returns byte representation of real
var formatInputReal = function (value) {
return formatInputInt(new BigNumber(value).times(new BigNumber(2).pow(128)));
};
var dynamicTypeBytes = function (type, value) { var dynamicTypeBytes = function (type, value) {
// TODO: decide what to do with array of strings // TODO: decide what to do with array of strings
if (arrayType(type) || type === 'string') // only string itself that is dynamic; stringX is static length. if (arrayType(type) || type === 'string') // only string itself that is dynamic; stringX is static length.
return f.formatInputInt(value.length); return formatInputInt(value.length);
return ""; return "";
}; };
var inputTypes = types.inputTypes(); /// Setups input formatters for solidity types
/// @returns an array of input formatters
var setupInputTypes = function () {
return [
{ type: prefixedType('uint'), format: formatInputInt },
{ type: prefixedType('int'), format: formatInputInt },
{ type: prefixedType('hash'), format: formatInputInt },
{ type: prefixedType('string'), format: formatInputString },
{ type: prefixedType('real'), format: formatInputReal },
{ type: prefixedType('ureal'), format: formatInputReal },
{ type: namedType('address'), format: formatInputInt },
{ type: namedType('bool'), format: formatInputBool }
];
};
var inputTypes = setupInputTypes();
/// Formats input params to bytes /// Formats input params to bytes
/// @param abi contract method inputs /// @param contract json abi
/// @param name of the method that we want to use
/// @param array of params that will be formatted to bytes /// @param array of params that will be formatted to bytes
/// @returns bytes representation of input params /// @returns bytes representation of input params
var formatInput = function (inputs, params) { var toAbiInput = function (json, methodName, params) {
var bytes = ""; var bytes = "";
var padding = c.ETH_PADDING * 2;
var method = getMethodWithName(json, methodName);
var padding = ETH_PADDING * 2;
/// first we iterate in search for dynamic /// first we iterate in search for dynamic
inputs.forEach(function (input, index) { method.inputs.forEach(function (input, index) {
bytes += dynamicTypeBytes(input.type, params[index]); bytes += dynamicTypeBytes(input.type, params[index]);
}); });
inputs.forEach(function (input, i) { method.inputs.forEach(function (input, i) {
var typeMatch = false; var typeMatch = false;
for (var j = 0; j < inputTypes.length && !typeMatch; j++) { for (var j = 0; j < inputTypes.length && !typeMatch; j++) {
typeMatch = inputTypes[j].type(inputs[i].type, params[i]); typeMatch = inputTypes[j].type(method.inputs[i].type, params[i]);
} }
if (!typeMatch) { if (!typeMatch) {
displayTypeError(inputs[i].type); console.error('input parser does not support type: ' + method.inputs[i].type);
} }
var formatter = inputTypes[j - 1].format; var formatter = inputTypes[j - 1].format;
var toAppend = ""; var toAppend = "";
if (arrayType(inputs[i].type)) if (arrayType(method.inputs[i].type))
toAppend = params[i].reduce(function (acc, curr) { toAppend = params[i].reduce(function (acc, curr) {
return acc + formatter(curr); return acc + formatter(curr);
}, ""); }, "");
@ -83,44 +201,118 @@ var formatInput = function (inputs, params) {
return bytes; return bytes;
}; };
/// Check if input value is negative
/// @param value is hex format
/// @returns true if it is negative, otherwise false
var signedIsNegative = function (value) {
return (new BigNumber(value.substr(0, 1), 16).toString(2).substr(0, 1)) === '1';
};
/// Formats input right-aligned input bytes to int
/// @returns right-aligned input bytes formatted to int
var formatOutputInt = function (value) {
value = value || "0";
// check if it's negative number
// it it is, return two's complement
if (signedIsNegative(value)) {
return new BigNumber(value, 16).minus(new BigNumber('ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', 16)).minus(1);
}
return new BigNumber(value, 16);
};
/// Formats big right-aligned input bytes to uint
/// @returns right-aligned input bytes formatted to uint
var formatOutputUInt = function (value) {
value = value || "0";
return new BigNumber(value, 16);
};
/// @returns input bytes formatted to real
var formatOutputReal = function (value) {
return formatOutputInt(value).dividedBy(new BigNumber(2).pow(128));
};
/// @returns input bytes formatted to ureal
var formatOutputUReal = function (value) {
return formatOutputUInt(value).dividedBy(new BigNumber(2).pow(128));
};
/// @returns right-aligned input bytes formatted to hex
var formatOutputHash = function (value) {
return "0x" + value;
};
/// @returns right-aligned input bytes formatted to bool
var formatOutputBool = function (value) {
return value === '0000000000000000000000000000000000000000000000000000000000000001' ? true : false;
};
/// @returns left-aligned input bytes formatted to ascii string
var formatOutputString = function (value) {
return web3.toAscii(value);
};
/// @returns right-aligned input bytes formatted to address
var formatOutputAddress = function (value) {
return "0x" + value.slice(value.length - 40, value.length);
};
var dynamicBytesLength = function (type) { var dynamicBytesLength = function (type) {
if (arrayType(type) || type === 'string') // only string itself that is dynamic; stringX is static length. if (arrayType(type) || type === 'string') // only string itself that is dynamic; stringX is static length.
return c.ETH_PADDING * 2; return ETH_PADDING * 2;
return 0; return 0;
}; };
var outputTypes = types.outputTypes(); /// Setups output formaters for solidity types
/// @returns an array of output formatters
var setupOutputTypes = function () {
return [
{ type: prefixedType('uint'), format: formatOutputUInt },
{ type: prefixedType('int'), format: formatOutputInt },
{ type: prefixedType('hash'), format: formatOutputHash },
{ type: prefixedType('string'), format: formatOutputString },
{ type: prefixedType('real'), format: formatOutputReal },
{ type: prefixedType('ureal'), format: formatOutputUReal },
{ type: namedType('address'), format: formatOutputAddress },
{ type: namedType('bool'), format: formatOutputBool }
];
};
var outputTypes = setupOutputTypes();
/// Formats output bytes back to param list /// Formats output bytes back to param list
/// @param contract abi method outputs /// @param contract json abi
/// @param name of the method that we want to use
/// @param bytes representtion of output /// @param bytes representtion of output
/// @returns array of output params /// @returns array of output params
var formatOutput = function (outs, output) { var fromAbiOutput = function (json, methodName, output) {
output = output.slice(2); output = output.slice(2);
var result = []; var result = [];
var padding = c.ETH_PADDING * 2; var method = getMethodWithName(json, methodName);
var padding = ETH_PADDING * 2;
var dynamicPartLength = outs.reduce(function (acc, curr) { var dynamicPartLength = method.outputs.reduce(function (acc, curr) {
return acc + dynamicBytesLength(curr.type); return acc + dynamicBytesLength(curr.type);
}, 0); }, 0);
var dynamicPart = output.slice(0, dynamicPartLength); var dynamicPart = output.slice(0, dynamicPartLength);
output = output.slice(dynamicPartLength); output = output.slice(dynamicPartLength);
outs.forEach(function (out, i) { method.outputs.forEach(function (out, i) {
var typeMatch = false; var typeMatch = false;
for (var j = 0; j < outputTypes.length && !typeMatch; j++) { for (var j = 0; j < outputTypes.length && !typeMatch; j++) {
typeMatch = outputTypes[j].type(outs[i].type); typeMatch = outputTypes[j].type(method.outputs[i].type);
} }
if (!typeMatch) { if (!typeMatch) {
displayTypeError(outs[i].type); console.error('output parser does not support type: ' + method.outputs[i].type);
} }
var formatter = outputTypes[j - 1].format; var formatter = outputTypes[j - 1].format;
if (arrayType(outs[i].type)) { if (arrayType(method.outputs[i].type)) {
var size = f.formatOutputUInt(dynamicPart.slice(0, padding)); var size = formatOutputUInt(dynamicPart.slice(0, padding));
dynamicPart = dynamicPart.slice(padding); dynamicPart = dynamicPart.slice(padding);
var array = []; var array = [];
for (var k = 0; k < size; k++) { for (var k = 0; k < size; k++) {
@ -129,7 +321,7 @@ var formatOutput = function (outs, output) {
} }
result.push(array); result.push(array);
} }
else if (types.prefixedType('string')(outs[i].type)) { else if (prefixedType('string')(method.outputs[i].type)) {
dynamicPart = dynamicPart.slice(padding); dynamicPart = dynamicPart.slice(padding);
result.push(formatter(output.slice(0, padding))); result.push(formatter(output.slice(0, padding)));
output = output.slice(padding); output = output.slice(padding);
@ -142,18 +334,30 @@ var formatOutput = function (outs, output) {
return result; return result;
}; };
/// @returns display name for method eg. multiply(uint256) -> multiply
var methodDisplayName = function (method) {
var length = method.indexOf('(');
return length !== -1 ? method.substr(0, length) : method;
};
/// @returns overloaded part of method's name
var methodTypeName = function (method) {
/// TODO: make it not vulnerable
var length = method.indexOf('(');
return length !== -1 ? method.substr(length + 1, method.length - 1 - (length + 1)) : "";
};
/// @param json abi for contract /// @param json abi for contract
/// @returns input parser object for given json abi /// @returns input parser object for given json abi
/// TODO: refactor creating the parser, do not double logic from contract
var inputParser = function (json) { var inputParser = function (json) {
var parser = {}; var parser = {};
json.forEach(function (method) { json.forEach(function (method) {
var displayName = utils.extractDisplayName(method.name); var displayName = methodDisplayName(method.name);
var typeName = utils.extractTypeName(method.name); var typeName = methodTypeName(method.name);
var impl = function () { var impl = function () {
var params = Array.prototype.slice.call(arguments); var params = Array.prototype.slice.call(arguments);
return formatInput(method.inputs, params); return toAbiInput(json, method.name, params);
}; };
if (parser[displayName] === undefined) { if (parser[displayName] === undefined) {
@ -172,11 +376,11 @@ var outputParser = function (json) {
var parser = {}; var parser = {};
json.forEach(function (method) { json.forEach(function (method) {
var displayName = utils.extractDisplayName(method.name); var displayName = methodDisplayName(method.name);
var typeName = utils.extractTypeName(method.name); var typeName = methodTypeName(method.name);
var impl = function (output) { var impl = function (output) {
return formatOutput(method.outputs, output); return fromAbiOutput(json, method.name, output);
}; };
if (parser[displayName] === undefined) { if (parser[displayName] === undefined) {
@ -189,22 +393,18 @@ var outputParser = function (json) {
return parser; return parser;
}; };
/// @param function/event name for which we want to get signature /// @param method name for which we want to get method signature
/// @returns signature of function/event with given name /// @returns (promise) contract method signature for method with given name
var signatureFromAscii = function (name) { var methodSignature = function (name) {
return web3.sha3(web3.fromAscii(name)).slice(0, 2 + c.ETH_SIGNATURE_LENGTH * 2); return web3.sha3(web3.fromAscii(name)).slice(0, 2 + ETH_METHOD_SIGNATURE_LENGTH * 2);
};
var eventSignatureFromAscii = function (name) {
return web3.sha3(web3.fromAscii(name));
}; };
module.exports = { module.exports = {
inputParser: inputParser, inputParser: inputParser,
outputParser: outputParser, outputParser: outputParser,
formatInput: formatInput, methodSignature: methodSignature,
formatOutput: formatOutput, methodDisplayName: methodDisplayName,
signatureFromAscii: signatureFromAscii, methodTypeName: methodTypeName,
eventSignatureFromAscii: eventSignatureFromAscii getMethodWithName: getMethodWithName
}; };

View file

@ -1,56 +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 const.js
* @authors:
* Marek Kotewicz <marek@ethdev.com>
* @date 2015
*/
/// required to define ETH_BIGNUMBER_ROUNDING_MODE
if (process.env.NODE_ENV !== 'build') {
var BigNumber = require('bignumber.js'); // jshint ignore:line
}
var ETH_UNITS = [
'wei',
'Kwei',
'Mwei',
'Gwei',
'szabo',
'finney',
'ether',
'grand',
'Mether',
'Gether',
'Tether',
'Pether',
'Eether',
'Zether',
'Yether',
'Nether',
'Dether',
'Vether',
'Uether'
];
module.exports = {
ETH_PADDING: 32,
ETH_SIGNATURE_LENGTH: 4,
ETH_UNITS: ETH_UNITS,
ETH_BIGNUMBER_ROUNDING_MODE: { ROUNDING_MODE: BigNumber.ROUND_DOWN }
};

View file

@ -20,153 +20,8 @@
* @date 2014 * @date 2014
*/ */
var web3 = require('./web3'); var web3 = require('./web3'); // jshint ignore:line
var abi = require('./abi'); var abi = require('./abi');
var utils = require('./utils');
var eventImpl = require('./event');
var exportNatspecGlobals = function (vars) {
// it's used byt natspec.js
// TODO: figure out better way to solve this
web3._currentContractAbi = vars.abi;
web3._currentContractAddress = vars.address;
web3._currentContractMethodName = vars.method;
web3._currentContractMethodParams = vars.params;
};
var addFunctionRelatedPropertiesToContract = function (contract) {
contract.call = function (options) {
contract._isTransact = false;
contract._options = options;
return contract;
};
contract.transact = function (options) {
contract._isTransact = true;
contract._options = options;
return contract;
};
contract._options = {};
['gas', 'gasPrice', 'value', 'from'].forEach(function(p) {
contract[p] = function (v) {
contract._options[p] = v;
return contract;
};
});
};
var addFunctionsToContract = function (contract, desc, address) {
var inputParser = abi.inputParser(desc);
var outputParser = abi.outputParser(desc);
// create contract functions
utils.filterFunctions(desc).forEach(function (method) {
var displayName = utils.extractDisplayName(method.name);
var typeName = utils.extractTypeName(method.name);
var impl = function () {
var params = Array.prototype.slice.call(arguments);
var signature = abi.signatureFromAscii(method.name);
var parsed = inputParser[displayName][typeName].apply(null, params);
var options = contract._options || {};
options.to = address;
options.data = signature + parsed;
var isTransact = contract._isTransact === true || (contract._isTransact !== false && !method.constant);
var collapse = options.collapse !== false;
// reset
contract._options = {};
contract._isTransact = null;
if (isTransact) {
exportNatspecGlobals({
abi: desc,
address: address,
method: method.name,
params: params
});
// transactions do not have any output, cause we do not know, when they will be processed
web3.eth.transact(options);
return;
}
var output = web3.eth.call(options);
var ret = outputParser[displayName][typeName](output);
if (collapse)
{
if (ret.length === 1)
ret = ret[0];
else if (ret.length === 0)
ret = null;
}
return ret;
};
if (contract[displayName] === undefined) {
contract[displayName] = impl;
}
contract[displayName][typeName] = impl;
});
};
var addEventRelatedPropertiesToContract = function (contract, desc, address) {
contract.address = address;
contract._onWatchEventResult = function (data) {
var matchingEvent = event.getMatchingEvent(utils.filterEvents(desc));
var parser = eventImpl.outputParser(matchingEvent);
return parser(data);
};
Object.defineProperty(contract, 'topic', {
get: function() {
return utils.filterEvents(desc).map(function (e) {
return abi.eventSignatureFromAscii(e.name);
});
}
});
};
var addEventsToContract = function (contract, desc, address) {
// create contract events
utils.filterEvents(desc).forEach(function (e) {
var impl = function () {
var params = Array.prototype.slice.call(arguments);
var signature = abi.eventSignatureFromAscii(e.name);
var event = eventImpl.inputParser(address, signature, e);
var o = event.apply(null, params);
o._onWatchEventResult = function (data) {
var parser = eventImpl.outputParser(e);
return parser(data);
};
return web3.eth.watch(o);
};
// this property should be used by eth.filter to check if object is an event
impl._isEvent = true;
var displayName = utils.extractDisplayName(e.name);
var typeName = utils.extractTypeName(e.name);
if (contract[displayName] === undefined) {
contract[displayName] = impl;
}
contract[displayName][typeName] = impl;
});
};
/** /**
* This method should be called when we want to call / transact some solidity method from javascript * This method should be called when we want to call / transact some solidity method from javascript
@ -192,11 +47,10 @@ var addEventsToContract = function (contract, desc, address) {
var contract = function (address, desc) { var contract = function (address, desc) {
desc.forEach(function (method) {
// workaround for invalid assumption that method.name is the full anonymous prototype of the method. // workaround for invalid assumption that method.name is the full anonymous prototype of the method.
// it's not. it's just the name. the rest of the code assumes it's actually the anonymous // it's not. it's just the name. the rest of the code assumes it's actually the anonymous
// prototype, so we make it so as a workaround. // prototype, so we make it so as a workaround.
// TODO: we may not want to modify input params, maybe use copy instead?
desc.forEach(function (method) {
if (method.name.indexOf('(') === -1) { if (method.name.indexOf('(') === -1) {
var displayName = method.name; var displayName = method.name;
var typeName = method.inputs.map(function(i){return i.type; }).join(); var typeName = method.inputs.map(function(i){return i.type; }).join();
@ -204,11 +58,85 @@ var contract = function (address, desc) {
} }
}); });
var inputParser = abi.inputParser(desc);
var outputParser = abi.outputParser(desc);
var result = {}; var result = {};
addFunctionRelatedPropertiesToContract(result);
addFunctionsToContract(result, desc, address); result.call = function (options) {
addEventRelatedPropertiesToContract(result, desc, address); result._isTransact = false;
addEventsToContract(result, desc, address); result._options = options;
return result;
};
result.transact = function (options) {
result._isTransact = true;
result._options = options;
return result;
};
result._options = {};
['gas', 'gasPrice', 'value', 'from'].forEach(function(p) {
result[p] = function (v) {
result._options[p] = v;
return result;
};
});
desc.forEach(function (method) {
var displayName = abi.methodDisplayName(method.name);
var typeName = abi.methodTypeName(method.name);
var impl = function () {
var params = Array.prototype.slice.call(arguments);
var signature = abi.methodSignature(method.name);
var parsed = inputParser[displayName][typeName].apply(null, params);
var options = result._options || {};
options.to = address;
options.data = signature + parsed;
var isTransact = result._isTransact === true || (result._isTransact !== false && !method.constant);
var collapse = options.collapse !== false;
// reset
result._options = {};
result._isTransact = null;
if (isTransact) {
// it's used byt natspec.js
// TODO: figure out better way to solve this
web3._currentContractAbi = desc;
web3._currentContractAddress = address;
web3._currentContractMethodName = method.name;
web3._currentContractMethodParams = params;
// transactions do not have any output, cause we do not know, when they will be processed
web3.eth.transact(options);
return;
}
var output = web3.eth.call(options);
var ret = outputParser[displayName][typeName](output);
if (collapse)
{
if (ret.length === 1)
ret = ret[0];
else if (ret.length === 0)
ret = null;
}
return ret;
};
if (result[displayName] === undefined) {
result[displayName] = impl;
}
result[displayName][typeName] = impl;
});
return result; return result;
}; };

View file

@ -1,135 +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 event.js
* @authors:
* Marek Kotewicz <marek@ethdev.com>
* @date 2014
*/
var abi = require('./abi');
var utils = require('./utils');
/// filter inputs array && returns only indexed (or not) inputs
/// @param inputs array
/// @param bool if result should be an array of indexed params on not
/// @returns array of (not?) indexed params
var filterInputs = function (inputs, indexed) {
return inputs.filter(function (current) {
return current.indexed === indexed;
});
};
var inputWithName = function (inputs, name) {
var index = utils.findIndex(inputs, function (input) {
return input.name === name;
});
if (index === -1) {
console.error('indexed param with name ' + name + ' not found');
return undefined;
}
return inputs[index];
};
var indexedParamsToTopics = function (event, indexed) {
// sort keys?
return Object.keys(indexed).map(function (key) {
var inputs = [inputWithName(filterInputs(event.inputs, true), key)];
var value = indexed[key];
if (value instanceof Array) {
return value.map(function (v) {
return abi.formatInput(inputs, [v]);
});
}
return abi.formatInput(inputs, [value]);
});
};
var inputParser = function (address, signature, event) {
// valid options are 'earliest', 'latest', 'offset' and 'max', as defined for 'eth.watch'
return function (indexed, options) {
var o = options || {};
o.address = address;
o.topic = [];
o.topic.push(signature);
if (indexed) {
o.topic = o.topic.concat(indexedParamsToTopics(event, indexed));
}
return o;
};
};
var getArgumentsObject = function (inputs, indexed, notIndexed) {
var indexedCopy = indexed.slice();
var notIndexedCopy = notIndexed.slice();
return inputs.reduce(function (acc, current) {
var value;
if (current.indexed)
value = indexed.splice(0, 1)[0];
else
value = notIndexed.splice(0, 1)[0];
acc[current.name] = value;
return acc;
}, {});
};
var outputParser = function (event) {
return function (output) {
var result = {
event: utils.extractDisplayName(event.name),
number: output.number,
args: {}
};
if (!output.topic) {
return result;
}
var indexedOutputs = filterInputs(event.inputs, true);
var indexedData = "0x" + output.topic.slice(1, output.topic.length).map(function (topic) { return topic.slice(2); }).join("");
var indexedRes = abi.formatOutput(indexedOutputs, indexedData);
var notIndexedOutputs = filterInputs(event.inputs, false);
var notIndexedRes = abi.formatOutput(notIndexedOutputs, output.data);
result.args = getArgumentsObject(event.inputs, indexedRes, notIndexedRes);
return result;
};
};
var getMatchingEvent = function (events, payload) {
for (var i = 0; i < events.length; i++) {
var signature = abi.eventSignatureFromAscii(events[i].name);
if (signature === payload.topic[0]) {
return events[i];
}
}
return undefined;
};
module.exports = {
inputParser: inputParser,
outputParser: outputParser,
getMatchingEvent: getMatchingEvent
};

View file

@ -27,45 +27,18 @@ var web3 = require('./web3'); // jshint ignore:line
/// should be used when we want to watch something /// should be used when we want to watch something
/// it's using inner polling mechanism and is notified about changes /// it's using inner polling mechanism and is notified about changes
/// TODO: change 'options' name cause it may be not the best matching one, since we have events
var Filter = function(options, impl) { var Filter = function(options, impl) {
if (typeof options !== "string") {
// topics property is deprecated, warn about it!
if (options.topics) {
console.warn('"topics" is deprecated, use "topic" instead');
}
this._onWatchResult = options._onWatchEventResult;
// evaluate lazy properties
options = {
to: options.to,
topic: options.topic,
earliest: options.earliest,
latest: options.latest,
max: options.max,
skip: options.skip,
address: options.address
};
}
this.impl = impl; this.impl = impl;
this.callbacks = []; this.callbacks = [];
this.id = impl.newFilter(options); this.id = impl.newFilter(options);
web3.provider.startPolling({method: impl.changed, params: [this.id]}, this.id, this.trigger.bind(this)); web3.provider.startPolling({call: impl.changed, args: [this.id]}, this.id, this.trigger.bind(this));
}; };
/// alias for changed* /// alias for changed*
Filter.prototype.arrived = function(callback) { Filter.prototype.arrived = function(callback) {
this.changed(callback); this.changed(callback);
}; };
Filter.prototype.happened = function(callback) {
this.changed(callback);
};
/// gets called when there is new eth/shh message /// gets called when there is new eth/shh message
Filter.prototype.changed = function(callback) { Filter.prototype.changed = function(callback) {
@ -76,8 +49,7 @@ Filter.prototype.changed = function(callback) {
Filter.prototype.trigger = function(messages) { Filter.prototype.trigger = function(messages) {
for (var i = 0; i < this.callbacks.length; i++) { for (var i = 0; i < this.callbacks.length; i++) {
for (var j = 0; j < messages.length; j++) { for (var j = 0; j < messages.length; j++) {
var message = this._onWatchResult ? this._onWatchResult(messages[j]) : messages[j]; this.callbacks[i].call(this, messages[j]);
this.callbacks[i].call(this, message);
} }
} }
}; };

View file

@ -1,154 +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 formatters.js
* @authors:
* Marek Kotewicz <marek@ethdev.com>
* @date 2015
*/
if (process.env.NODE_ENV !== 'build') {
var BigNumber = require('bignumber.js'); // jshint ignore:line
}
var utils = require('./utils');
var c = require('./const');
/// @param string string to be padded
/// @param number of characters that result string should have
/// @param sign, by default 0
/// @returns right aligned string
var padLeft = function (string, chars, sign) {
return new Array(chars - string.length + 1).join(sign ? sign : "0") + string;
};
/// Formats input value to byte representation of int
/// If value is negative, return it's two's complement
/// If the value is floating point, round it down
/// @returns right-aligned byte representation of int
var formatInputInt = function (value) {
var padding = c.ETH_PADDING * 2;
if (value instanceof BigNumber || typeof value === 'number') {
if (typeof value === 'number')
value = new BigNumber(value);
BigNumber.config(c.ETH_BIGNUMBER_ROUNDING_MODE);
value = value.round();
if (value.lessThan(0))
value = new BigNumber("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16).plus(value).plus(1);
value = value.toString(16);
}
else if (value.indexOf('0x') === 0)
value = value.substr(2);
else if (typeof value === 'string')
value = formatInputInt(new BigNumber(value));
else
value = (+value).toString(16);
return padLeft(value, padding);
};
/// Formats input value to byte representation of string
/// @returns left-algined byte representation of string
var formatInputString = function (value) {
return utils.fromAscii(value, c.ETH_PADDING).substr(2);
};
/// Formats input value to byte representation of bool
/// @returns right-aligned byte representation bool
var formatInputBool = function (value) {
return '000000000000000000000000000000000000000000000000000000000000000' + (value ? '1' : '0');
};
/// Formats input value to byte representation of real
/// Values are multiplied by 2^m and encoded as integers
/// @returns byte representation of real
var formatInputReal = function (value) {
return formatInputInt(new BigNumber(value).times(new BigNumber(2).pow(128)));
};
/// Check if input value is negative
/// @param value is hex format
/// @returns true if it is negative, otherwise false
var signedIsNegative = function (value) {
return (new BigNumber(value.substr(0, 1), 16).toString(2).substr(0, 1)) === '1';
};
/// Formats input right-aligned input bytes to int
/// @returns right-aligned input bytes formatted to int
var formatOutputInt = function (value) {
value = value || "0";
// check if it's negative number
// it it is, return two's complement
if (signedIsNegative(value)) {
return new BigNumber(value, 16).minus(new BigNumber('ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', 16)).minus(1);
}
return new BigNumber(value, 16);
};
/// Formats big right-aligned input bytes to uint
/// @returns right-aligned input bytes formatted to uint
var formatOutputUInt = function (value) {
value = value || "0";
return new BigNumber(value, 16);
};
/// @returns input bytes formatted to real
var formatOutputReal = function (value) {
return formatOutputInt(value).dividedBy(new BigNumber(2).pow(128));
};
/// @returns input bytes formatted to ureal
var formatOutputUReal = function (value) {
return formatOutputUInt(value).dividedBy(new BigNumber(2).pow(128));
};
/// @returns right-aligned input bytes formatted to hex
var formatOutputHash = function (value) {
return "0x" + value;
};
/// @returns right-aligned input bytes formatted to bool
var formatOutputBool = function (value) {
return value === '0000000000000000000000000000000000000000000000000000000000000001' ? true : false;
};
/// @returns left-aligned input bytes formatted to ascii string
var formatOutputString = function (value) {
return utils.toAscii(value);
};
/// @returns right-aligned input bytes formatted to address
var formatOutputAddress = function (value) {
return "0x" + value.slice(value.length - 40, value.length);
};
module.exports = {
formatInputInt: formatInputInt,
formatInputString: formatInputString,
formatInputBool: formatInputBool,
formatInputReal: formatInputReal,
formatOutputInt: formatOutputInt,
formatOutputUInt: formatOutputUInt,
formatOutputReal: formatOutputReal,
formatOutputUReal: formatOutputUReal,
formatOutputHash: formatOutputHash,
formatOutputBool: formatOutputBool,
formatOutputString: formatOutputString,
formatOutputAddress: formatOutputAddress
};

View file

@ -30,16 +30,40 @@ var HttpSyncProvider = function (host) {
this.host = host || 'http://localhost:8080'; this.host = host || 'http://localhost:8080';
}; };
/// Transforms inner message to proper jsonrpc object
/// @param inner message object
/// @returns jsonrpc object
function formatJsonRpcObject(object) {
return {
jsonrpc: '2.0',
method: object.call,
params: object.args,
id: object._id
};
}
/// Transforms jsonrpc object to inner message
/// @param incoming jsonrpc message
/// @returns inner message object
function formatJsonRpcMessage(message) {
var object = JSON.parse(message);
return {
_id: object.id,
data: object.result,
error: object.error
};
}
HttpSyncProvider.prototype.send = function (payload) { HttpSyncProvider.prototype.send = function (payload) {
//var data = formatJsonRpcObject(payload); var data = formatJsonRpcObject(payload);
var request = new XMLHttpRequest(); var request = new XMLHttpRequest();
request.open('POST', this.host, false); request.open('POST', this.host, false);
request.send(JSON.stringify(payload)); request.send(JSON.stringify(data));
// check request.status // check request.status
var result = request.responseText; return request.responseText;
return JSON.parse(result);
}; };
module.exports = HttpSyncProvider; module.exports = HttpSyncProvider;

View file

@ -1,65 +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 jsonrpc.js
* @authors:
* Marek Kotewicz <marek@ethdev.com>
* @date 2015
*/
var messageId = 1;
/// Should be called to valid json create payload object
/// @param method of jsonrpc call, required
/// @param params, an array of method params, optional
/// @returns valid jsonrpc payload object
var toPayload = function (method, params) {
if (!method)
console.error('jsonrpc method should be specified!');
return {
jsonrpc: '2.0',
method: method,
params: params || [],
id: messageId++
};
};
/// Should be called to check if jsonrpc response is valid
/// @returns true if response is valid, otherwise false
var isValidResponse = function (response) {
return !!response &&
!response.error &&
response.jsonrpc === '2.0' &&
typeof response.id === 'number' &&
response.result !== undefined; // only undefined is not valid json object
};
/// Should be called to create batch payload object
/// @param messages, an array of objects with method (required) and params (optional) fields
var toBatchPayload = function (messages) {
return messages.map(function (message) {
return toPayload(message.method, message.params);
});
};
module.exports = {
toPayload: toPayload,
isValidResponse: isValidResponse,
toBatchPayload: toBatchPayload
};

View file

@ -23,9 +23,7 @@
* @date 2014 * @date 2014
*/ */
var web3 = require('./web3'); var web3 = require('./web3'); // jshint ignore:line
var jsonrpc = require('./jsonrpc');
/** /**
* Provider manager object prototype * Provider manager object prototype
@ -39,38 +37,48 @@ var jsonrpc = require('./jsonrpc');
var ProviderManager = function() { var ProviderManager = function() {
this.polls = []; this.polls = [];
this.provider = undefined; this.provider = undefined;
this.id = 1;
var self = this; var self = this;
var poll = function () { var poll = function () {
if (self.provider) {
self.polls.forEach(function (data) { self.polls.forEach(function (data) {
var result = self.send(data.data); data.data._id = self.id;
self.id++;
var result = self.provider.send(data.data);
if (!(result instanceof Array) || result.length === 0) { result = JSON.parse(result);
// dont call the callback if result is not an array, or empty one
if (result.error || !(result.result instanceof Array) || result.result.length === 0) {
return; return;
} }
data.callback(result); data.callback(result.result);
}); });
}
setTimeout(poll, 1000); setTimeout(poll, 1000);
}; };
poll(); poll();
}; };
/// sends outgoing requests /// sends outgoing requests
/// @params data - an object with at least 'method' property
ProviderManager.prototype.send = function(data) { ProviderManager.prototype.send = function(data) {
var payload = jsonrpc.toPayload(data.method, data.params);
data.args = data.args || [];
data._id = this.id++;
if (this.provider === undefined) { if (this.provider === undefined) {
console.error('provider is not set'); console.error('provider is not set');
return null; return null;
} }
var result = this.provider.send(payload); //TODO: handle error here?
var result = this.provider.send(data);
result = JSON.parse(result);
if (!jsonrpc.isValidResponse(result)) { if (result.error) {
console.log(result); console.log(result.error);
return null; return null;
} }

View file

@ -25,8 +25,7 @@ var QtSyncProvider = function () {
}; };
QtSyncProvider.prototype.send = function (payload) { QtSyncProvider.prototype.send = function (payload) {
var result = navigator.qt.callMethod(JSON.stringify(payload)); return navigator.qt.callMethod(JSON.stringify(payload));
return JSON.parse(result);
}; };
module.exports = QtSyncProvider; module.exports = QtSyncProvider;

View file

@ -1,79 +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 types.js
* @authors:
* Marek Kotewicz <marek@ethdev.com>
* @date 2015
*/
var f = require('./formatters');
/// @param expected type prefix (string)
/// @returns function which checks if type has matching prefix. if yes, returns true, otherwise false
var prefixedType = function (prefix) {
return function (type) {
return type.indexOf(prefix) === 0;
};
};
/// @param expected type name (string)
/// @returns function which checks if type is matching expected one. if yes, returns true, otherwise false
var namedType = function (name) {
return function (type) {
return name === type;
};
};
/// Setups input formatters for solidity types
/// @returns an array of input formatters
var inputTypes = function () {
return [
{ type: prefixedType('uint'), format: f.formatInputInt },
{ type: prefixedType('int'), format: f.formatInputInt },
{ type: prefixedType('hash'), format: f.formatInputInt },
{ type: prefixedType('string'), format: f.formatInputString },
{ type: prefixedType('real'), format: f.formatInputReal },
{ type: prefixedType('ureal'), format: f.formatInputReal },
{ type: namedType('address'), format: f.formatInputInt },
{ type: namedType('bool'), format: f.formatInputBool }
];
};
/// Setups output formaters for solidity types
/// @returns an array of output formatters
var outputTypes = function () {
return [
{ type: prefixedType('uint'), format: f.formatOutputUInt },
{ type: prefixedType('int'), format: f.formatOutputInt },
{ type: prefixedType('hash'), format: f.formatOutputHash },
{ type: prefixedType('string'), format: f.formatOutputString },
{ type: prefixedType('real'), format: f.formatOutputReal },
{ type: prefixedType('ureal'), format: f.formatOutputUReal },
{ type: namedType('address'), format: f.formatOutputAddress },
{ type: namedType('bool'), format: f.formatOutputBool }
];
};
module.exports = {
prefixedType: prefixedType,
namedType: namedType,
inputTypes: inputTypes,
outputTypes: outputTypes
};

View file

@ -1,142 +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 utils.js
* @authors:
* Marek Kotewicz <marek@ethdev.com>
* @date 2015
*/
var c = require('./const');
/// Finds first index of array element matching pattern
/// @param array
/// @param callback pattern
/// @returns index of element
var findIndex = function (array, callback) {
var end = false;
var i = 0;
for (; i < array.length && !end; i++) {
end = callback(array[i]);
}
return end ? i - 1 : -1;
};
/// @returns ascii string representation of hex value prefixed with 0x
var 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 = parseInt(hex.substr(i, 2), 16);
if (code === 0) {
break;
}
str += String.fromCharCode(code);
}
return str;
};
var 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;
};
/// @returns hex representation (prefixed by 0x) of ascii string
var fromAscii = function(str, pad) {
pad = pad === undefined ? 0 : pad;
var hex = toHex(str);
while (hex.length < pad*2)
hex += "00";
return "0x" + hex;
};
/// @returns display name for function/event eg. multiply(uint256) -> multiply
var extractDisplayName = function (name) {
var length = name.indexOf('(');
return length !== -1 ? name.substr(0, length) : name;
};
/// @returns overloaded part of function/event name
var extractTypeName = function (name) {
/// TODO: make it invulnerable
var length = name.indexOf('(');
return length !== -1 ? name.substr(length + 1, name.length - 1 - (length + 1)).replace(' ', '') : "";
};
/// Filters all function from input abi
/// @returns abi array with filtered objects of type 'function'
var filterFunctions = function (json) {
return json.filter(function (current) {
return current.type === 'function';
});
};
/// Filters all events form input abi
/// @returns abi array with filtered objects of type 'event'
var filterEvents = function (json) {
return json.filter(function (current) {
return current.type === 'event';
});
};
/// used to transform value/string to eth string
/// TODO: use BigNumber.js to parse int
/// TODO: add tests for it!
var toEth = function (str) {
var val = typeof str === "string" ? str.indexOf('0x') === 0 ? parseInt(str.substr(2), 16) : parseInt(str) : str;
var unit = 0;
var units = c.ETH_UNITS;
while (val > 3000 && unit < units.length - 1)
{
val /= 1000;
unit++;
}
var s = val.toString().length < val.toFixed(2).length ? val.toString() : val.toFixed(2);
var replaceFunction = function($0, $1, $2) {
return $1 + ',' + $2;
};
while (true) {
var o = s;
s = s.replace(/(\d)(\d\d\d[\.\,])/, replaceFunction);
if (o === s)
break;
}
return s + ' ' + units[unit];
};
module.exports = {
findIndex: findIndex,
toAscii: toAscii,
fromAscii: fromAscii,
extractDisplayName: extractDisplayName,
extractTypeName: extractTypeName,
filterFunctions: filterFunctions,
filterEvents: filterEvents,
toEth: toEth
};

View file

@ -27,7 +27,27 @@ if (process.env.NODE_ENV !== 'build') {
var BigNumber = require('bignumber.js'); var BigNumber = require('bignumber.js');
} }
var utils = require('./utils'); var ETH_UNITS = [
'wei',
'Kwei',
'Mwei',
'Gwei',
'szabo',
'finney',
'ether',
'grand',
'Mether',
'Gether',
'Tether',
'Pether',
'Eether',
'Zether',
'Yether',
'Nether',
'Dether',
'Vether',
'Uether'
];
/// @returns an array of objects describing web3 api methods /// @returns an array of objects describing web3 api methods
var web3Methods = function () { var web3Methods = function () {
@ -136,8 +156,8 @@ var setupMethods = function (obj, methods) {
var args = Array.prototype.slice.call(arguments); var args = Array.prototype.slice.call(arguments);
var call = typeof method.call === 'function' ? method.call(args) : method.call; var call = typeof method.call === 'function' ? method.call(args) : method.call;
return web3.provider.send({ return web3.provider.send({
method: call, call: call,
params: args args: args
}); });
}; };
}); });
@ -150,15 +170,15 @@ var setupProperties = function (obj, properties) {
var proto = {}; var proto = {};
proto.get = function () { proto.get = function () {
return web3.provider.send({ return web3.provider.send({
method: property.getter call: property.getter
}); });
}; };
if (property.setter) { if (property.setter) {
proto.set = function (val) { proto.set = function (val) {
return web3.provider.send({ return web3.provider.send({
method: property.setter, call: property.setter,
params: [val] args: [val]
}); });
}; };
} }
@ -172,11 +192,43 @@ var web3 = {
_events: {}, _events: {},
providers: {}, 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;
},
/// @returns ascii string representation of hex value prefixed with 0x /// @returns ascii string representation of hex value prefixed with 0x
toAscii: utils.toAscii, 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 = parseInt(hex.substr(i, 2), 16);
if(code === 0) {
break;
}
str += String.fromCharCode(code);
}
return str;
},
/// @returns hex representation (prefixed by 0x) of ascii string /// @returns hex representation (prefixed by 0x) of ascii string
fromAscii: utils.fromAscii, fromAscii: function(str, pad) {
pad = pad === undefined ? 0 : pad;
var hex = this.toHex(str);
while(hex.length < pad*2)
hex += "00";
return "0x" + hex;
},
/// @returns decimal representaton of hex value prefixed by 0x /// @returns decimal representaton of hex value prefixed by 0x
toDecimal: function (val) { toDecimal: function (val) {
@ -191,7 +243,29 @@ var web3 = {
}, },
/// used to transform value/string to eth string /// used to transform value/string to eth string
toEth: utils.toEth, /// TODO: use BigNumber.js to parse int
toEth: function(str) {
var val = typeof str === "string" ? str.indexOf('0x') === 0 ? parseInt(str.substr(2), 16) : parseInt(str) : str;
var unit = 0;
var units = ETH_UNITS;
while (val > 3000 && unit < units.length - 1)
{
val /= 1000;
unit++;
}
var s = val.toString().length < val.toFixed(2).length ? val.toString() : val.toFixed(2);
var replaceFunction = function($0, $1, $2) {
return $1 + ',' + $2;
};
while (true) {
var o = s;
s = s.replace(/(\d)(\d\d\d[\.\,])/, replaceFunction);
if (o === s)
break;
}
return s + ' ' + units[unit];
},
/// eth object prototype /// eth object prototype
eth: { eth: {
@ -204,15 +278,8 @@ var web3 = {
return ret; return ret;
}; };
}, },
watch: function (params) {
/// @param filter may be a string, object or event return new web3.filter(params, ethWatch);
/// @param indexed is optional, this is an object with optional event indexed params
/// @param options is optional, this is an object with optional event options ('max'...)
watch: function (filter, indexed, options) {
if (filter._isEvent) {
return filter(indexed, options);
}
return new web3.filter(filter, ethWatch);
} }
}, },
@ -221,12 +288,15 @@ var web3 = {
/// shh object prototype /// shh object prototype
shh: { shh: {
watch: function (params) {
/// @param filter may be a string, object or event return new web3.filter(params, shhWatch);
watch: function (filter, indexed) {
return new web3.filter(filter, shhWatch);
} }
}, },
/// @returns true if provider is installed
haveProvider: function() {
return !!web3.provider.provider;
}
}; };
/// setups all api methods /// setups all api methods
@ -249,6 +319,7 @@ var shhWatch = {
setupMethods(shhWatch, shhWatchMethods()); setupMethods(shhWatch, shhWatchMethods());
web3.setProvider = function(provider) { web3.setProvider = function(provider) {
//provider.onmessage = messageHandler; // there will be no async calls, to remove
web3.provider.set(provider); web3.provider.set(provider);
}; };

View file

@ -1,7 +1,7 @@
{ {
"name": "ethereum.js", "name": "ethereum.js",
"namespace": "ethereum", "namespace": "ethereum",
"version": "0.0.13", "version": "0.0.10",
"description": "Ethereum Compatible JavaScript API", "description": "Ethereum Compatible JavaScript API",
"main": "./index.js", "main": "./index.js",
"directories": { "directories": {

View file

@ -1,7 +1,7 @@
var assert = require('assert'); var assert = require('assert');
var web3 = require('../index.js'); var web3 = require('../index.js');
var u = require('./test.utils.js'); var u = require('./utils.js');
describe('web3', function() { describe('web3', function() {
describe('db', function() { describe('db', function() {

View file

@ -1,6 +1,6 @@
var assert = require('assert'); var assert = require('assert');
var web3 = require('../index.js'); var web3 = require('../index.js');
var u = require('./test.utils.js'); var u = require('./utils.js');
describe('web3', function() { describe('web3', function() {
describe('eth', function() { describe('eth', function() {

View file

@ -1,6 +1,6 @@
var assert = require('assert'); var assert = require('assert');
var web3 = require('../index.js'); var web3 = require('../index.js');
var u = require('./test.utils.js'); var u = require('./utils.js');
describe('web3', function() { describe('web3', function() {
describe('shh', function() { describe('shh', function() {

View file

@ -1,6 +1,6 @@
var assert = require('assert'); var assert = require('assert');
var web3 = require('../index.js'); var web3 = require('../index.js');
var u = require('./test.utils.js'); var u = require('./utils.js');
describe('web3', function() { describe('web3', function() {
u.methodExists(web3, 'sha3'); u.methodExists(web3, 'sha3');

View file

@ -1,83 +0,0 @@
<!doctype>
<html>
<head>
<title>Ethereum</title>
<script type="text/javascript" src="../ext/bignumber.min.js"></script>
<script type="text/javascript" src="../ext/ethereum.js/dist/ethereum.js"></script>
<style type="text/css">
body {
font-family: Helvetica;
}
div.logo {
width: 192px;
margin: 40px auto;
}
</style>
</head>
<body>
<div class="logo"><img src="logo.png"></img></div>
<h1>Info</h1>
<table width="100%">
<tr>
<td>Block number</td>
<td id="number"></td>
</tr>
<tr>
<td>Peer count</td>
<td id="peer_count"></td>
</tr>
<tr>
<td>Accounts</td>
<td id="accounts"></td>
</tr>
<tr>
<td>Gas price</td>
<td id="gas_price"></td>
</tr>
<tr>
<td>Mining</td>
<td id="mining"></td>
</tr>
<tr>
<td>Listening</td>
<td id="listening"></td>
</tr>
<tr>
<td>Coinbase</td>
<td id="coinbase"></td>
</tr>
</table>
</body>
<script type="text/javascript">
var web3 = require('web3');
var eth = web3.eth;
web3.setProvider(new web3.providers.HttpSyncProvider('http://localhost:8545'));
document.querySelector("#number").innerHTML = eth.number;
document.querySelector("#coinbase").innerHTML = eth.coinbase
document.querySelector("#peer_count").innerHTML = eth.peerCount;
document.querySelector("#accounts").innerHTML = eth.accounts;
document.querySelector("#gas_price").innerHTML = eth.gasPrice;
document.querySelector("#mining").innerHTML = eth.mining;
document.querySelector("#listening").innerHTML = eth.listening;
eth.watch('pending').changed(function() {
console.log("pending changed");
});
eth.watch('chain').changed(function() {
document.querySelector("#number").innerHTML = eth.number;
});
</script>
</html>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View file

@ -9,14 +9,19 @@ import Ethereum 1.0
import "../ext/filter.js" as Eth import "../ext/filter.js" as Eth
import "../ext/http.js" as Http import "../ext/http.js" as Http
ApplicationWindow { ApplicationWindow {
id: root id: root
//flags: Qt.FramelessWindowHint
// Use this to make the window frameless. But then you'll need to do move and resize by hand
property var ethx : Eth.ethx property var ethx : Eth.ethx
width: 1200 width: 1200
height: 820 height: 820
minimumWidth: 300 minimumHeight: 600
minimumWidth: 800
title: "Mist" title: "Mist"
@ -33,9 +38,11 @@ ApplicationWindow {
// Takes care of loading all default plugins // Takes care of loading all default plugins
Component.onCompleted: { Component.onCompleted: {
var wallet = addPlugin("./views/wallet.qml", {noAdd: true, close: false, section: "ethereum", active: true});
addPlugin("./views/miner.qml", {noAdd: true, close: false, section: "ethereum", active: true});
addPlugin("./views/catalog.qml", {noAdd: true, close: false, section: "begin"});
var wallet = addPlugin("./views/wallet.qml", {noAdd: true, close: false, section: "ethereum", active: true});
addPlugin("./views/miner.qml", {noAdd: true, close: false, section: "ethereum", active: true});
addPlugin("./views/transaction.qml", {noAdd: true, close: false, section: "legacy"}); addPlugin("./views/transaction.qml", {noAdd: true, close: false, section: "legacy"});
addPlugin("./views/whisper.qml", {noAdd: true, close: false, section: "legacy"}); addPlugin("./views/whisper.qml", {noAdd: true, close: false, section: "legacy"});
addPlugin("./views/chain.qml", {noAdd: true, close: false, section: "legacy"}); addPlugin("./views/chain.qml", {noAdd: true, close: false, section: "legacy"});
@ -44,7 +51,7 @@ ApplicationWindow {
mainSplit.setView(wallet.view, wallet.menuItem); mainSplit.setView(wallet.view, wallet.menuItem);
newBrowserTab(eth.assetPath("html/home.html")); newBrowserTab("http://localhost:3000/chat/MfJhJuAamRS3JuGbu");
// Command setup // Command setup
gui.sendCommand(0) gui.sendCommand(0)
@ -113,6 +120,8 @@ ApplicationWindow {
activeView(window.view, window.menuItem); activeView(window.view, window.menuItem);
} }
menuBar: MenuBar { menuBar: MenuBar {
Menu { Menu {
title: "File" title: "File"
@ -137,7 +146,7 @@ ApplicationWindow {
text: "New tab" text: "New tab"
shortcut: "Ctrl+t" shortcut: "Ctrl+t"
onTriggered: { onTriggered: {
newBrowserTab("about:blank"); newBrowserTab("http://etherian.io");
} }
} }
@ -245,6 +254,8 @@ ApplicationWindow {
statusBar: StatusBar { statusBar: StatusBar {
//height: 32 //height: 32
visible: false
id: statusBar id: statusBar
Label { Label {
//y: 6 //y: 6
@ -264,11 +275,10 @@ ApplicationWindow {
} }
Label { Label {
//y: 6
id: lastBlockLabel id: lastBlockLabel
objectName: "lastBlockLabel" objectName: "lastBlockLabel"
visible: true visible: true
text: "" text: "---"
font.pixelSize: 10 font.pixelSize: 10
anchors.right: peerGroup.left anchors.right: peerGroup.left
anchors.rightMargin: 5 anchors.rightMargin: 5
@ -323,6 +333,11 @@ ApplicationWindow {
id: mainSplit id: mainSplit
anchors.fill: parent anchors.fill: parent
resizing: false resizing: false
handleDelegate: Item {
Rectangle {
anchors.fill: parent
}
}
function setView(view, menu) { function setView(view, menu) {
for(var i = 0; i < views.length; i++) { for(var i = 0; i < views.length; i++) {
@ -359,10 +374,71 @@ ApplicationWindow {
********************/ ********************/
Rectangle { Rectangle {
id: menu id: menu
Layout.minimumWidth: 210 Layout.minimumWidth: 192
Layout.maximumWidth: 210 Layout.maximumWidth: 192
FontLoader {
id: sourceSansPro
source: "fonts/SourceSansPro-Regular.ttf"
}
FontLoader {
source: "fonts/SourceSansPro-Semibold.ttf"
}
FontLoader {
source: "fonts/SourceSansPro-Bold.ttf"
}
FontLoader {
source: "fonts/SourceSansPro-Black.ttf"
}
FontLoader {
source: "fonts/SourceSansPro-Light.ttf"
}
FontLoader {
source: "fonts/SourceSansPro-ExtraLight.ttf"
}
FontLoader {
id: simpleLineIcons
source: "fonts/Simple-Line-Icons.ttf"
}
Rectangle {
color: "steelblue"
anchors.fill: parent
MouseArea {
anchors.fill: parent
property real lastMouseX: 0
property real lastMouseY: 0
onPressed: {
lastMouseX = mouseX
lastMouseY = mouseY
}
onPositionChanged: {
root.x += (mouseX - lastMouseX)
root.y += (mouseY - lastMouseY)
}
/*onDoubleClicked: {
//!maximized ? view.set_max() : view.set_normal()}
visibility = "Minimized"
}*/
}
}
anchors.top: parent.top anchors.top: parent.top
color: "#ececec" Rectangle {
width: parent.height
height: parent.width
anchors.centerIn: parent
rotation: 90
gradient: Gradient {
GradientStop { position: 0.0; color: "#E2DEDE" }
GradientStop { position: 0.1; color: "#EBE8E8" }
GradientStop { position: 1.0; color: "#EBE8E8" }
}
}
Component { Component {
id: menuItemTemplate id: menuItemTemplate
@ -377,10 +453,20 @@ ApplicationWindow {
property alias secondaryTitle: secondary.text property alias secondaryTitle: secondary.text
function setSelection(on) { function setSelection(on) {
sel.visible = on sel.visible = on
if (this.closable == true) {
closeIcon.visible = on
}
} }
width: 206 function setAsBigButton(on) {
height: 28 newAppButton.visible = on
label.visible = !on
buttonLabel.visible = on
}
width: 192
height: 55
color: "#00000000" color: "#00000000"
anchors { anchors {
@ -388,6 +474,19 @@ ApplicationWindow {
leftMargin: 4 leftMargin: 4
} }
Rectangle {
// New App Button
id: newAppButton
visible: false
anchors.fill: parent
anchors.rightMargin: 8
border.width: 0
radius: 5
height: 55
width: 180
color: "#F3F1F3"
}
Rectangle { Rectangle {
id: sel id: sel
visible: false visible: false
@ -396,8 +495,7 @@ ApplicationWindow {
Rectangle { Rectangle {
id: r id: r
anchors.fill: parent anchors.fill: parent
border.color: "#CCCCCC" border.width: 0
border.width: 1
radius: 5 radius: 5
color: "#FFFFFFFF" color: "#FFFFFFFF"
} }
@ -409,75 +507,129 @@ ApplicationWindow {
} }
width: 10 width: 10
color: "#FFFFFFFF" color: "#FFFFFFFF"
border.width:0
Rectangle { Rectangle {
// Small line on top of selection. What's this for?
anchors { anchors {
left: parent.left left: parent.left
right: parent.right right: parent.right
top: parent.top top: parent.top
} }
height: 1 height: 1
color: "#CCCCCC" color: "#FFFFFF"
} }
Rectangle { Rectangle {
// Small line on bottom of selection. What's this for again?
anchors { anchors {
left: parent.left left: parent.left
right: parent.right right: parent.right
bottom: parent.bottom bottom: parent.bottom
} }
height: 1 height: 1
color: "#CCCCCC" color: "#FFFFFF"
} }
} }
} }
MouseArea { MouseArea {
anchors.fill: parent anchors.fill: parent
hoverEnabled: true
onClicked: { onClicked: {
activeView(view, menuItem); activeView(view, menuItem);
} }
onEntered: {
if (parent.closable == true) {
closeIcon.visible = sel.visible
}
}
onExited: {
closeIcon.visible = false
}
} }
Image { Image {
id: icon id: icon
height: 20 height: 24
width: 20 width: 24
anchors { anchors {
left: parent.left left: parent.left
verticalCenter: parent.verticalCenter verticalCenter: parent.verticalCenter
leftMargin: 3 leftMargin: 6
} }
}
Text {
id: buttonLabel
visible: false
text: "GO TO NEW APP"
font.family: sourceSansPro.name
font.weight: Font.DemiBold
anchors.horizontalCenter: parent.horizontalCenter
anchors.verticalCenter: parent.verticalCenter
color: "#AAA0A0"
}
Text {
id: label
font.family: sourceSansPro.name
font.weight: Font.DemiBold
anchors {
left: icon.right
verticalCenter: parent.verticalCenter
leftMargin: 6
// verticalCenterOffset: -10
}
x:250
color: "#665F5F"
font.pixelSize: 14
}
Text {
id: secondary
font.family: sourceSansPro.name
font.weight: Font.Light
anchors {
left: icon.right
leftMargin: 6
top: label.bottom
}
color: "#6691C2"
font.pixelSize: 12
}
Rectangle {
id: closeIcon
visible: false
width: 10
height: 10
color: "#FFFFFF"
anchors {
fill: icon
}
MouseArea { MouseArea {
anchors.fill: parent anchors.fill: parent
onClicked: { onClicked: {
menuItem.closeApp() menuItem.closeApp()
} }
} }
}
Text { Text {
id: label
font.family: simpleLineIcons.name
anchors { anchors {
left: icon.right centerIn: parent
verticalCenter: parent.verticalCenter }
leftMargin: 3 color: "#665F5F"
font.pixelSize: 18
text: "\ue082"
}
} }
color: "#0D0A01"
font.pixelSize: 12
}
Text {
id: secondary
anchors {
right: parent.right
rightMargin: 8
verticalCenter: parent.verticalCenter
}
color: "#AEADBE"
font.pixelSize: 12
}
function closeApp() { function closeApp() {
@ -509,6 +661,9 @@ ApplicationWindow {
var section; var section;
switch(options.section) { switch(options.section) {
case "begin":
section = menuBegin
break;
case "ethereum": case "ethereum":
section = menuDefault; section = menuDefault;
break; break;
@ -529,6 +684,10 @@ ApplicationWindow {
} }
comp.closable = options.close; comp.closable = options.close;
if (options.section === "begin") {
comp.setAsBigButton(true)
}
return comp return comp
} }
@ -540,16 +699,34 @@ ApplicationWindow {
anchors.right: parent.right anchors.right: parent.right
spacing: 3 spacing: 3
Text {
text: "ETHEREUM"
font.bold: true ColumnLayout {
id: menuBegin
spacing: 3
anchors { anchors {
left: parent.left left: parent.left
leftMargin: 5 right: parent.right
} }
color: "#888888"
} }
Rectangle {
height: 55
color: "transparent"
Text {
text: "ETHEREUM"
font.family: sourceSansPro.name
font.weight: Font.DemiBold
anchors {
left: parent.left
top: parent.verticalCenter
leftMargin: 16
}
color: "#AAA0A0"
}
}
ColumnLayout { ColumnLayout {
id: menuDefault id: menuDefault
spacing: 3 spacing: 3
@ -559,15 +736,20 @@ ApplicationWindow {
} }
} }
Rectangle {
height: 55
color: "transparent"
Text { Text {
text: "NET" text: "APPS"
font.bold: true font.family: sourceSansPro.name
font.weight: Font.DemiBold
anchors { anchors {
left: parent.left left: parent.left
leftMargin: 5 top: parent.verticalCenter
leftMargin: 16
}
color: "#AAA0A0"
} }
color: "#888888"
} }
ColumnLayout { ColumnLayout {
@ -579,15 +761,22 @@ ApplicationWindow {
} }
} }
Rectangle {
height: 55
color: "transparent"
Text { Text {
text: "DEBUG" text: "DEBUG"
font.bold: true font.family: sourceSansPro.name
font.weight: Font.DemiBold
anchors { anchors {
left: parent.left left: parent.left
leftMargin: 5 top: parent.verticalCenter
leftMargin: 16
} }
color: "#888888" color: "#AAA0A0"
} }
}
ColumnLayout { ColumnLayout {
id: menuLegacy id: menuLegacy

View file

@ -56,12 +56,34 @@ Rectangle {
//uriNav.text = uri.text.replace(/(^https?\:\/\/(?:www\.)?)([a-zA-Z0-9_\-]*\.\w{2,3})(.*)/, "$1$2<span style='color:#CCC'>$3</span>"); //uriNav.text = uri.text.replace(/(^https?\:\/\/(?:www\.)?)([a-zA-Z0-9_\-]*\.\w{2,3})(.*)/, "$1$2<span style='color:#CCC'>$3</span>");
uriNav.text = uri; uriNav.text = uri;
} else { } else {
// Prevent inf loop. // Prevent inf loop.
window.cleanPath = false; window.cleanPath = false;
} }
} }
function showFullUrlBar(on){
if (on) {
//appTitle.visible = false
//appDomain.visible = false
//uriNav.visible = true
clickAnywhereOnApp.visible = true
navBar.state = "fullUrlVisible"
} else {
//appTitle.visible = true
//appDomain.visible = true
//uriNav.visible = false
clickAnywhereOnApp.visible = false
navBar.state = "titleVisible"
}
}
Component.onCompleted: { Component.onCompleted: {
} }
@ -71,75 +93,234 @@ Rectangle {
anchors.fill: parent anchors.fill: parent
state: "inspectorShown" state: "inspectorShown"
MouseArea {
id: clickAnywhereOnApp
z:15
//hoverEnabled: true
anchors.fill: parent
/*hoverEnabled: true*/
onClicked: {
showFullUrlBar(false);
}
/*Rectangle {
anchors.fill: parent
color: "#88888888"
}*/
}
RowLayout { RowLayout {
id: navBar id: navBar
height: 40 height: 74
z: 20
anchors { anchors {
left: parent.left left: parent.left
right: parent.right right: parent.right
leftMargin: 7
} }
Button { Button {
id: back id: back
onClicked: { onClicked: {
webview.goBack() webview.goBack()
} }
anchors{
left: parent.left
leftMargin: 6
}
style: ButtonStyle { style: ButtonStyle {
background: Image { background: Image {
source: "../../back.png" source: "../../backButton.png"
width: 30 width: 20
height: 30 height: 30
} }
} }
} }
TextField { Rectangle {
id: appInfoPane
height: 28
color: "#FFFFFF"
radius: 6
MouseArea {
anchors.fill: parent
z: 10
hoverEnabled: true
onEntered: {
showFullUrlBar(true);
}
}
anchors { anchors {
left: back.right left: back.right
right: toggleInspector.left right: parent.right
leftMargin: 10 leftMargin: 10
rightMargin: 10 rightMargin: 10
} }
text: webview.url;
id: uriNav
y: parent.height / 2 - this.height / 2
Keys.onReturnPressed: { Text {
webview.url = this.text; id: appTitle
} text: "LOADING"
} font.bold: true
font.capitalization: Font.AllUppercase
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
Button {
id: toggleInspector
anchors { anchors {
right: parent.right left: parent.left
} right: parent.horizontalCenter
iconSource: "../../bug.png" top: parent.top
onClicked: { bottom: parent.bottom
// XXX soon rightMargin: 10
return
if(inspector.visible == true){
inspector.visible = false
}else{
inspector.visible = true
inspector.url = webview.experimental.remoteInspectorUrl
}
}
} }
color: "#928484"
} }
// Border Text {
Rectangle { id: appDomain
id: divider text: "loading domain"
font.bold: false
horizontalAlignment: Text.AlignLeft
verticalAlignment: Text.AlignVCenter
anchors {
left: parent.horizontalCenter
right: parent.right
top: parent.top
bottom: parent.bottom
leftMargin: 10
}
color: "#C0AFAF"
}
TextField {
id: uriNav
opacity: 0.0
anchors { anchors {
left: parent.left left: parent.left
right: parent.right right: parent.right
top: navBar.bottom leftMargin: 16
}
horizontalAlignment: Text.AlignHCenter
style: TextFieldStyle {
textColor: "#928484"
background: Rectangle {
border.width: 0
color: "transparent"
}
}
text: webview.url;
y: parent.height / 2 - this.height / 2
z: 20
activeFocusOnPress: true
Keys.onReturnPressed: {
webview.url = this.text;
}
/* onFocusedChanged: {
if (focused) {
//uriNav.selectAll();
}
}*/
}
z:2
}
Rectangle {
id: appInfoPaneShadow
width: 10
height: 30
color: "#BDB6B6"
radius: 6
anchors {
left: back.right
right: parent.right
leftMargin:10
rightMargin:10
top: parent.top
topMargin: 23
}
z:1
}
Rectangle {
id: navBarBackground
anchors.fill: parent
gradient: Gradient {
GradientStop { position: 0.0; color: "#F6F1F2" }
GradientStop { position: 1.0; color: "#DED5D5" }
} }
z:-1 z:-1
height: 1 }
color: "#CCCCCC"
states: [
State {
name: "fullUrlVisible"
PropertyChanges {
target: appTitle
anchors.rightMargin: -50
opacity: 0.0
}
PropertyChanges {
target: appDomain
anchors.leftMargin: -50
opacity: 0.0
}
PropertyChanges {
target: uriNav
anchors.leftMargin: 0
opacity: 1.0
}
},
State {
name: "titleVisible"
PropertyChanges {
target: appTitle
anchors.rightMargin: 10
opacity: 1.0
}
PropertyChanges {
target: appDomain
anchors.leftMargin: 10
opacity: 1.0
}
PropertyChanges {
target: uriNav
anchors.leftMargin: -50
opacity: 0.0
}
}
]
transitions: [
// This adds a transition that defaults to applying to all state changes
Transition {
// This applies a default NumberAnimation to any changes a state change makes to x or y properties
NumberAnimation {
properties: "anchors.leftMargin, anchors.rightMargin, opacity"
easing.type: Easing.InOutQuad //Easing.InOutBack
duration: 300
}
}
]
} }
WebEngineView { WebEngineView {
@ -149,16 +330,44 @@ Rectangle {
left: parent.left left: parent.left
right: parent.right right: parent.right
bottom: parent.bottom bottom: parent.bottom
top: divider.bottom top: navBar.bottom
} }
z: 10
onLoadingChanged: { onLoadingChanged: {
if (loadRequest.status == WebEngineView.LoadSucceededStatus) { if (loadRequest.status == WebEngineView.LoadSucceededStatus) {
webview.runJavaScript("document.title", function(pageTitle) { webview.runJavaScript("document.title", function(pageTitle) {
menuItem.title = pageTitle; menuItem.title = pageTitle;
}); });
//var topBarStyle
webView.runJavaScript("document.querySelector(\"meta[name='ethereum-dapp-url-bar-style']\").getAttribute(\"content\")", function(topBarStyle){
if (topBarStyle=="transparent") {
// Adjust for a transparent sidebar Dapp
navBarBackground.visible = false;
back.visible = false;
appInfoPane.anchors.leftMargin = -16;
appInfoPaneShadow.anchors.leftMargin = -16;
webview.anchors.topMargin = -74;
webview.runJavaScript("document.querySelector('body').classList.add('ethereum-dapp-url-bar-style-transparent')")
};
});
webview.runJavaScript(eth.readFile("bignumber.min.js")); webview.runJavaScript(eth.readFile("bignumber.min.js"));
webview.runJavaScript(eth.readFile("ethereum.js/dist/ethereum.js")); webview.runJavaScript(eth.readFile("ethereum.js/dist/ethereum.js"));
var cleanTitle = webview.url.toString()
var matches = cleanTitle.match(/^[a-z]*\:\/\/([^\/?#]+)(?:[\/?#]|$)/i);
var domain = matches && matches[1];
appDomain.text = domain //webview.url.replace("a", "z")
appTitle.text = webview.title
showFullUrlBar(false);
} }
} }
onJavaScriptConsoleMessage: { onJavaScriptConsoleMessage: {
@ -208,4 +417,3 @@ Rectangle {
] ]
} }
} }

View file

@ -0,0 +1,209 @@
import QtQuick 2.0
import QtQuick.Controls 1.0;
import QtQuick.Controls.Styles 1.0
import QtQuick.Layouts 1.0;
import QtWebEngine 1.0
//import QtWebEngine.experimental 1.0
import QtQuick.Window 2.0;
Rectangle {
id: window
anchors.fill: parent
color: "#00000000"
property var title: ""
property var iconSource: ""
property var menuItem
property var hideUrl: true
property alias url: webview.url
property alias windowTitle: webview.title
property alias webView: webview
property var cleanPath: false
property var open: function(url) {
if(!window.cleanPath) {
var uri = url;
if(!/.*\:\/\/.*/.test(uri)) {
uri = "http://" + uri;
}
var reg = /(^https?\:\/\/(?:www\.)?)([a-zA-Z0-9_\-]*\.eth)(.*)/
if(reg.test(uri)) {
uri.replace(reg, function(match, pre, domain, path) {
uri = pre;
var lookup = eth.lookupDomain(domain.substring(0, domain.length - 4));
var ip = [];
for(var i = 0, l = lookup.length; i < l; i++) {
ip.push(lookup.charCodeAt(i))
}
if(ip.length != 0) {
uri += lookup;
} else {
uri += domain;
}
uri += path;
});
}
window.cleanPath = true;
webview.url = uri;
//uriNav.text = uri.text.replace(/(^https?\:\/\/(?:www\.)?)([a-zA-Z0-9_\-]*\.\w{2,3})(.*)/, "$1$2<span style='color:#CCC'>$3</span>");
uriNav.text = uri;
} else {
// Prevent inf loop.
window.cleanPath = false;
}
}
Component.onCompleted: {
}
Item {
objectName: "root"
id: root
anchors.fill: parent
state: "inspectorShown"
RowLayout {
id: navBar
height: 184
z: 20
anchors {
left: parent.left
right: parent.right
}
Rectangle {
id: appInfoPane
height: 28
color: "#efefef"
radius: 6
z:25
MouseArea {
anchors.fill: parent
z: 10
hoverEnabled: true
onEntered: {
uriNav.visible = true
appTitle.visible = false
appDomain.visible = false
}
}
anchors {
left: parent.left
right: parent.right
leftMargin: 10
rightMargin: 10
top: parent.verticalCenter
topMargin: 23
}
TextField {
id: uriNav
anchors {
left: parent.left
right: parent.right
leftMargin: 16
top: parent.verticalCenter
topMargin: -10
}
horizontalAlignment: Text.AlignHCenter
style: TextFieldStyle {
textColor: "#928484"
background: Rectangle {
border.width: 0
color: "transparent"
}
}
text: "Type the address of a new Dapp";
y: parent.height / 2 - this.height / 2
z: 30
activeFocusOnPress: true
Keys.onReturnPressed: {
newBrowserTab(this.text);
this.text = "Type the address of a new Dapp";
}
}
}
Rectangle {
id: appInfoPaneShadow
width: 10
height: 30
color: "#BDB6B6"
radius: 6
z: 15
anchors {
left: parent.left
right: parent.right
leftMargin:10
rightMargin:10
top: parent.verticalCenter
topMargin: 23
}
}
}
WebEngineView {
objectName: "webView"
id: webview
anchors.fill: parent
onLoadingChanged: {
if (loadRequest.status == WebEngineView.LoadSucceededStatus) {
webview.runJavaScript(eth.readFile("bignumber.min.js"));
webview.runJavaScript(eth.readFile("ethereum.js/dist/ethereum.js"));
}
}
onJavaScriptConsoleMessage: {
console.log(sourceID + ":" + lineNumber + ":" + JSON.stringify(message));
}
}
WebEngineView {
id: inspector
visible: false
z:10
anchors {
left: root.left
right: root.right
top: sizeGrip.bottom
bottom: root.bottom
}
}
states: [
State {
name: "inspectorShown"
PropertyChanges {
target: inspector
}
}
]
}
}

View file

@ -111,7 +111,7 @@ Rectangle {
if(initial){ if(initial){
blockModel.append({raw: block.raw, bloom: block.bloom, size: block.size, number: block.number, name: block.name, gasLimit: block.gasLimit, gasUsed: block.gasUsed, coinbase: block.coinbase, hash: block.hash, txs: txs, txAmount: amount, time: block.time, prettyTime: convertToPretty(block.time)}) blockModel.append({raw: block.raw, bloom: block.bloom, size: block.size, number: block.number, name: block.name, gasLimit: block.gasLimit, gasUsed: block.gasUsed, coinbase: block.coinbase, hash: block.hash, txs: txs, txAmount: amount, time: block.time, prettyTime: convertToPretty(block.time)})
} else { } else {
blockModel.insert(0, {raw: block.raw, bloom: block.bloom, size: block.size, number: block.number, name: block.name, gasLimit: block.gasLimit, gasUsed: block.gasUsed, coinbase: block.coinbase, hash: block.hash, txs: txs, txAmount: amount, time: block.time, prettyTime: convertToPretty(block.time)}) blockModel.insert(0, {bloom: block.bloom, size: block.size, number: block.number, name: block.name, gasLimit: block.gasLimit, gasUsed: block.gasUsed, coinbase: block.coinbase, hash: block.hash, txs: txs, txAmount: amount, time: block.time, prettyTime: convertToPretty(block.time)})
} }
} }

View file

@ -29,7 +29,6 @@ import (
"github.com/ethereum/go-ethereum/cmd/utils" "github.com/ethereum/go-ethereum/cmd/utils"
"github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethutil" "github.com/ethereum/go-ethereum/ethutil"
"github.com/ethereum/go-ethereum/state" "github.com/ethereum/go-ethereum/state"
"github.com/ethereum/go-ethereum/vm" "github.com/ethereum/go-ethereum/vm"
@ -155,17 +154,14 @@ func (self *DebuggerWindow) Debug(valueStr, gasStr, gasPriceStr, scriptStr, data
block := self.lib.eth.ChainManager().CurrentBlock() block := self.lib.eth.ChainManager().CurrentBlock()
msg := types.NewTransactionMessage(nil, value, gas, gasPrice, data) env := utils.NewEnv(self.lib.eth.ChainManager(), statedb, block, account.Address(), value)
env := core.NewEnv(statedb, self.lib.eth.ChainManager(), msg, block)
self.Logf("callsize %d", len(script)) self.Logf("callsize %d", len(script))
go func() { go func() {
pgas := new(big.Int).Set(gas)
ret, err := env.Call(account, contract.Address(), data, gas, gasPrice, ethutil.Big0) ret, err := env.Call(account, contract.Address(), data, gas, gasPrice, ethutil.Big0)
//ret, g, err := callerClosure.Call(evm, data)
rgas := new(big.Int).Sub(pgas, gas) tot := new(big.Int).Mul(env.Gas, gasPrice)
tot := new(big.Int).Mul(rgas, gasPrice) self.Logf("gas usage %v total price = %v (%v)", env.Gas, tot, ethutil.CurrencyToString(tot))
self.Logf("gas usage %v total price = %v (%v)", rgas, tot, ethutil.CurrencyToString(tot))
if err != nil { if err != nil {
self.Logln("exited with errors:", err) self.Logln("exited with errors:", err)
} else { } else {

View file

@ -51,7 +51,7 @@ var (
AddPeer string AddPeer string
MaxPeer int MaxPeer int
GenAddr bool GenAddr bool
SeedNode string UseSeed bool
SecretFile string SecretFile string
ExportDir string ExportDir string
NonInteractive bool NonInteractive bool
@ -111,12 +111,12 @@ func Init() {
flag.StringVar(&OutboundPort, "port", "30303", "listening port") flag.StringVar(&OutboundPort, "port", "30303", "listening port")
flag.BoolVar(&UseUPnP, "upnp", true, "enable UPnP support") flag.BoolVar(&UseUPnP, "upnp", true, "enable UPnP support")
flag.IntVar(&MaxPeer, "maxpeer", 30, "maximum desired peers") flag.IntVar(&MaxPeer, "maxpeer", 30, "maximum desired peers")
flag.IntVar(&RpcPort, "rpcport", 8545, "port to start json-rpc server on") flag.IntVar(&RpcPort, "rpcport", 8080, "port to start json-rpc server on")
flag.IntVar(&WsPort, "wsport", 40404, "port to start websocket rpc server on") flag.IntVar(&WsPort, "wsport", 40404, "port to start websocket rpc server on")
flag.BoolVar(&StartRpc, "rpc", true, "start rpc server") flag.BoolVar(&StartRpc, "rpc", true, "start rpc server")
flag.BoolVar(&StartWebSockets, "ws", false, "start websocket server") flag.BoolVar(&StartWebSockets, "ws", false, "start websocket server")
flag.BoolVar(&NonInteractive, "y", false, "non-interactive mode (say yes to confirmations)") flag.BoolVar(&NonInteractive, "y", false, "non-interactive mode (say yes to confirmations)")
flag.StringVar(&SeedNode, "seednode", "poc-8.ethdev.com:30303", "ip:port of seed node to connect to. Set to blank for skip") flag.BoolVar(&UseSeed, "seed", true, "seed peers")
flag.BoolVar(&GenAddr, "genaddr", false, "create a new priv/pub key") flag.BoolVar(&GenAddr, "genaddr", false, "create a new priv/pub key")
flag.StringVar(&NatType, "nat", "", "NAT support (UPNP|PMP) (none)") flag.StringVar(&NatType, "nat", "", "NAT support (UPNP|PMP) (none)")
flag.StringVar(&SecretFile, "import", "", "imports the file given (hex or mnemonic formats)") flag.StringVar(&SecretFile, "import", "", "imports the file given (hex or mnemonic formats)")

View file

@ -84,7 +84,7 @@ func run() error {
utils.RegisterInterrupt(func(os.Signal) { utils.RegisterInterrupt(func(os.Signal) {
gui.Stop() gui.Stop()
}) })
go utils.StartEthereum(ethereum, SeedNode) go utils.StartEthereum(ethereum, UseSeed)
fmt.Println("ETH stack took", time.Since(tstart)) fmt.Println("ETH stack took", time.Since(tstart))

View file

@ -136,7 +136,7 @@ func (ui *UiLib) Muted(content string) {
func (ui *UiLib) Connect(button qml.Object) { func (ui *UiLib) Connect(button qml.Object) {
if !ui.connected { if !ui.connected {
ui.eth.Start(SeedNode) ui.eth.Start(true)
ui.connected = true ui.connected = true
button.Set("enabled", false) button.Set("enabled", false)
} }

View file

@ -121,9 +121,9 @@ func exit(err error) {
os.Exit(status) os.Exit(status)
} }
func StartEthereum(ethereum *eth.Ethereum, SeedNode string) { func StartEthereum(ethereum *eth.Ethereum, UseSeed bool) {
clilogger.Infof("Starting %s", ethereum.ClientIdentity()) clilogger.Infof("Starting %s", ethereum.ClientIdentity())
err := ethereum.Start(SeedNode) err := ethereum.Start(UseSeed)
if err != nil { if err != nil {
exit(err) exit(err)
} }
@ -205,7 +205,7 @@ func StartWebSockets(eth *eth.Ethereum, wsPort int) {
clilogger.Infoln("Starting WebSockets") clilogger.Infoln("Starting WebSockets")
var err error var err error
eth.WsServer, err = rpcws.NewWebSocketServer(xeth.New(eth), wsPort) eth.WsServer, err = rpcws.NewWebSocketServer(eth, wsPort)
if err != nil { if err != nil {
clilogger.Errorf("Could not start RPC interface (port %v): %v", wsPort, err) clilogger.Errorf("Could not start RPC interface (port %v): %v", wsPort, err)
} else { } else {

98
cmd/utils/vm_env.go Normal file
View file

@ -0,0 +1,98 @@
/*
This file is part of go-ethereum
go-ethereum 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.
go-ethereum 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 go-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @authors
* Jeffrey Wilcke <i@jev.io>
*/
package utils
import (
"math/big"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/state"
"github.com/ethereum/go-ethereum/vm"
)
type VMEnv struct {
chain *core.ChainManager
state *state.StateDB
block *types.Block
transactor []byte
value *big.Int
depth int
Gas *big.Int
}
func NewEnv(chain *core.ChainManager, state *state.StateDB, block *types.Block, transactor []byte, value *big.Int) *VMEnv {
return &VMEnv{
chain: chain,
state: state,
block: block,
transactor: transactor,
value: value,
}
}
func (self *VMEnv) Origin() []byte { return self.transactor }
func (self *VMEnv) BlockNumber() *big.Int { return self.block.Number() }
func (self *VMEnv) PrevHash() []byte { return self.block.ParentHash() }
func (self *VMEnv) Coinbase() []byte { return self.block.Coinbase() }
func (self *VMEnv) Time() int64 { return self.block.Time() }
func (self *VMEnv) Difficulty() *big.Int { return self.block.Difficulty() }
func (self *VMEnv) GasLimit() *big.Int { return self.block.GasLimit() }
func (self *VMEnv) Value() *big.Int { return self.value }
func (self *VMEnv) State() *state.StateDB { return self.state }
func (self *VMEnv) Depth() int { return self.depth }
func (self *VMEnv) SetDepth(i int) { self.depth = i }
func (self *VMEnv) GetHash(n uint64) []byte {
if block := self.chain.GetBlockByNumber(n); block != nil {
return block.Hash()
}
return nil
}
func (self *VMEnv) AddLog(log state.Log) {
self.state.AddLog(log)
}
func (self *VMEnv) Transfer(from, to vm.Account, amount *big.Int) error {
return vm.Transfer(from, to, amount)
}
func (self *VMEnv) vm(addr, data []byte, gas, price, value *big.Int) *core.Execution {
return core.NewExecution(self, addr, data, gas, price, value)
}
func (self *VMEnv) Call(caller vm.ContextRef, addr, data []byte, gas, price, value *big.Int) ([]byte, error) {
exe := self.vm(addr, data, gas, price, value)
ret, err := exe.Call(addr, caller)
self.Gas = exe.Gas
return ret, err
}
func (self *VMEnv) CallCode(caller vm.ContextRef, addr, data []byte, gas, price, value *big.Int) ([]byte, error) {
exe := self.vm(caller.Address(), data, gas, price, value)
return exe.Call(addr, caller)
}
func (self *VMEnv) Create(caller vm.ContextRef, addr, data []byte, gas, price, value *big.Int) ([]byte, error, vm.ContextRef) {
exe := self.vm(addr, data, gas, price, value)
return exe.Create(caller)
}

View file

@ -17,10 +17,6 @@ import (
"gopkg.in/fatih/set.v0" "gopkg.in/fatih/set.v0"
) )
type PendingBlockEvent struct {
Block *types.Block
}
var statelogger = logger.NewLogger("BLOCK") var statelogger = logger.NewLogger("BLOCK")
type BlockProcessor struct { type BlockProcessor struct {
@ -72,37 +68,6 @@ func (sm *BlockProcessor) TransitionState(statedb *state.StateDB, parent, block
return receipts, nil return receipts, nil
} }
func (self *BlockProcessor) ApplyTransaction(coinbase *state.StateObject, state *state.StateDB, block *types.Block, tx *types.Transaction, usedGas *big.Int, transientProcess bool) (*types.Receipt, *big.Int, error) {
// If we are mining this block and validating we want to set the logs back to 0
state.EmptyLogs()
txGas := new(big.Int).Set(tx.Gas())
cb := state.GetStateObject(coinbase.Address())
st := NewStateTransition(NewEnv(state, self.bc, tx, block), tx, cb)
_, err := st.TransitionState()
txGas.Sub(txGas, st.gas)
// Update the state with pending changes
state.Update(txGas)
cumulative := new(big.Int).Set(usedGas.Add(usedGas, txGas))
receipt := types.NewReceipt(state.Root(), cumulative)
receipt.SetLogs(state.Logs())
receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
chainlogger.Debugln(receipt)
// Notify all subscribers
if !transientProcess {
go self.eventMux.Post(TxPostEvent{tx})
}
go self.eventMux.Post(state.Logs())
return receipt, txGas, err
}
func (self *BlockProcessor) ApplyTransactions(coinbase *state.StateObject, state *state.StateDB, block *types.Block, txs types.Transactions, transientProcess bool) (types.Receipts, types.Transactions, types.Transactions, types.Transactions, error) { func (self *BlockProcessor) ApplyTransactions(coinbase *state.StateObject, state *state.StateDB, block *types.Block, txs types.Transactions, transientProcess bool) (types.Receipts, types.Transactions, types.Transactions, types.Transactions, error) {
var ( var (
receipts types.Receipts receipts types.Receipts
@ -113,55 +78,82 @@ func (self *BlockProcessor) ApplyTransactions(coinbase *state.StateObject, state
cumulativeSum = new(big.Int) cumulativeSum = new(big.Int)
) )
for _, tx := range txs { done:
receipt, txGas, err := self.ApplyTransaction(coinbase, state, block, tx, totalUsedGas, transientProcess) for i, tx := range txs {
// If we are mining this block and validating we want to set the logs back to 0
state.EmptyLogs()
txGas := new(big.Int).Set(tx.Gas())
cb := state.GetStateObject(coinbase.Address())
st := NewStateTransition(NewEnv(state, self.bc, tx, block), tx, cb)
_, err = st.TransitionState()
if err != nil { if err != nil {
switch { switch {
case IsNonceErr(err): case IsNonceErr(err):
return nil, nil, nil, nil, err err = nil // ignore error
continue
case IsGasLimitErr(err): case IsGasLimitErr(err):
return nil, nil, nil, nil, err unhandled = txs[i:]
break done
default: default:
statelogger.Infoln(err) statelogger.Infoln(err)
erroneous = append(erroneous, tx) erroneous = append(erroneous, tx)
err = nil err = nil
} }
} }
txGas.Sub(txGas, st.gas)
cumulativeSum.Add(cumulativeSum, new(big.Int).Mul(txGas, tx.GasPrice()))
// Update the state with pending changes
state.Update(txGas)
cumulative := new(big.Int).Set(totalUsedGas.Add(totalUsedGas, txGas))
receipt := types.NewReceipt(state.Root(), cumulative)
receipt.SetLogs(state.Logs())
receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
chainlogger.Debugln(receipt)
// Notify all subscribers
if !transientProcess {
go self.eventMux.Post(TxPostEvent{tx})
}
receipts = append(receipts, receipt) receipts = append(receipts, receipt)
handled = append(handled, tx) handled = append(handled, tx)
cumulativeSum.Add(cumulativeSum, new(big.Int).Mul(txGas, tx.GasPrice())) if ethutil.Config.Diff && ethutil.Config.DiffType == "all" {
state.CreateOutputForDiff()
}
} }
block.Reward = cumulativeSum block.Reward = cumulativeSum
block.Header().GasUsed = totalUsedGas block.Header().GasUsed = totalUsedGas
if transientProcess {
go self.eventMux.Post(PendingBlockEvent{block})
}
return receipts, handled, unhandled, erroneous, err return receipts, handled, unhandled, erroneous, err
} }
func (sm *BlockProcessor) Process(block *types.Block) (td *big.Int, err error) { func (sm *BlockProcessor) Process(block *types.Block) (td *big.Int, msgs state.Messages, err error) {
// Processing a blocks may never happen simultaneously // Processing a blocks may never happen simultaneously
sm.mutex.Lock() sm.mutex.Lock()
defer sm.mutex.Unlock() defer sm.mutex.Unlock()
header := block.Header() header := block.Header()
if sm.bc.HasBlock(header.Hash()) { if sm.bc.HasBlock(header.Hash()) {
return nil, &KnownBlockError{header.Number, header.Hash()} return nil, nil, &KnownBlockError{header.Number, header.Hash()}
} }
if !sm.bc.HasBlock(header.ParentHash) { if !sm.bc.HasBlock(header.ParentHash) {
return nil, ParentError(header.ParentHash) return nil, nil, ParentError(header.ParentHash)
} }
parent := sm.bc.GetBlock(header.ParentHash) parent := sm.bc.GetBlock(header.ParentHash)
return sm.ProcessWithParent(block, parent) return sm.ProcessWithParent(block, parent)
} }
func (sm *BlockProcessor) ProcessWithParent(block, parent *types.Block) (td *big.Int, err error) { func (sm *BlockProcessor) ProcessWithParent(block, parent *types.Block) (td *big.Int, messages state.Messages, err error) {
sm.lastAttemptedBlock = block sm.lastAttemptedBlock = block
state := state.New(parent.Root(), sm.db) state := state.New(parent.Root(), sm.db)
@ -198,7 +190,7 @@ func (sm *BlockProcessor) ProcessWithParent(block, parent *types.Block) (td *big
return return
} }
if err = sm.AccumulateRewards(state, block, parent); err != nil { if err = sm.AccumelateRewards(state, block, parent); err != nil {
return return
} }
@ -211,10 +203,11 @@ func (sm *BlockProcessor) ProcessWithParent(block, parent *types.Block) (td *big
// Calculate the td for this block // Calculate the td for this block
td = CalculateTD(block, parent) td = CalculateTD(block, parent)
// Sync the current block's state to the database // Sync the current block's state to the database and cancelling out the deferred Undo
state.Sync() state.Sync()
// Set the block hashes for the current messages // Set the block hashes for the current messages
state.Manifest().SetHash(block.Hash()) state.Manifest().SetHash(block.Hash())
messages = state.Manifest().Messages
// Reset the manifest XXX We need this? // Reset the manifest XXX We need this?
state.Manifest().Reset() state.Manifest().Reset()
// Remove transactions from the pool // Remove transactions from the pool
@ -222,7 +215,7 @@ func (sm *BlockProcessor) ProcessWithParent(block, parent *types.Block) (td *big
chainlogger.Infof("processed block #%d (%x...)\n", header.Number, block.Hash()[0:4]) chainlogger.Infof("processed block #%d (%x...)\n", header.Number, block.Hash()[0:4])
return td, nil return td, messages, nil
} }
// Validates the current block. Returns an error if the block was invalid, // Validates the current block. Returns an error if the block was invalid,
@ -238,8 +231,9 @@ func (sm *BlockProcessor) ValidateBlock(block, parent *types.Block) error {
return fmt.Errorf("Difficulty check failed for block %v, %v", block.Header().Difficulty, expd) return fmt.Errorf("Difficulty check failed for block %v, %v", block.Header().Difficulty, expd)
} }
if block.Time() < parent.Time() { diff := block.Header().Time - parent.Header().Time
return ValidationError("Block timestamp not after prev block (%v - %v)", block.Header().Time, parent.Header().Time) if diff < 0 {
return ValidationError("Block timestamp less then prev block %v (%v - %v)", diff, block.Header().Time, sm.bc.CurrentBlock().Header().Time)
} }
if block.Time() > time.Now().Unix() { if block.Time() > time.Now().Unix() {
@ -254,7 +248,7 @@ func (sm *BlockProcessor) ValidateBlock(block, parent *types.Block) error {
return nil return nil
} }
func (sm *BlockProcessor) AccumulateRewards(statedb *state.StateDB, block, parent *types.Block) error { func (sm *BlockProcessor) AccumelateRewards(statedb *state.StateDB, block, parent *types.Block) error {
reward := new(big.Int).Set(BlockReward) reward := new(big.Int).Set(BlockReward)
ancestors := set.New() ancestors := set.New()
@ -275,10 +269,6 @@ func (sm *BlockProcessor) AccumulateRewards(statedb *state.StateDB, block, paren
return UncleError(fmt.Sprintf("Uncle's parent unknown (%x)", uncle.ParentHash[0:4])) return UncleError(fmt.Sprintf("Uncle's parent unknown (%x)", uncle.ParentHash[0:4]))
} }
if !sm.Pow.Verify(types.NewBlockWithHeader(uncle)) {
return ValidationError("Uncle's nonce is invalid (= %v)", ethutil.Bytes2Hex(uncle.Nonce))
}
r := new(big.Int) r := new(big.Int)
r.Mul(BlockReward, big.NewInt(15)).Div(r, big.NewInt(16)) r.Mul(BlockReward, big.NewInt(15)).Div(r, big.NewInt(16))
@ -293,6 +283,14 @@ func (sm *BlockProcessor) AccumulateRewards(statedb *state.StateDB, block, paren
// Reward amount of ether to the coinbase address // Reward amount of ether to the coinbase address
account.AddAmount(reward) account.AddAmount(reward)
statedb.Manifest().AddMessage(&state.Message{
To: block.Header().Coinbase,
Input: nil,
Origin: nil,
Timestamp: int64(block.Header().Time), Coinbase: block.Header().Coinbase, Number: block.Header().Number,
Value: new(big.Int).Add(reward, block.Reward),
})
return nil return nil
} }
@ -312,7 +310,7 @@ func (sm *BlockProcessor) GetMessages(block *types.Block) (messages []*state.Mes
defer state.Reset() defer state.Reset()
sm.TransitionState(state, parent, block) sm.TransitionState(state, parent, block)
sm.AccumulateRewards(state, block, parent) sm.AccumelateRewards(state, block, parent)
return state.Manifest().Messages, nil return state.Manifest().Messages, nil
} }
@ -333,7 +331,7 @@ func (sm *BlockProcessor) GetLogs(block *types.Block) (logs state.Logs, err erro
defer state.Reset() defer state.Reset()
sm.TransitionState(state, parent, block) sm.TransitionState(state, parent, block)
sm.AccumulateRewards(state, block, parent) sm.AccumelateRewards(state, block, parent)
return state.Logs(), nil return state.Logs(), nil
} }

View file

@ -359,7 +359,7 @@ func (bc *ChainManager) Stop() {
func (self *ChainManager) InsertChain(chain types.Blocks) error { func (self *ChainManager) InsertChain(chain types.Blocks) error {
for _, block := range chain { for _, block := range chain {
td, err := self.processor.Process(block) td, messages, err := self.processor.Process(block)
if err != nil { if err != nil {
if IsKnownBlockErr(err) { if IsKnownBlockErr(err) {
continue continue
@ -391,6 +391,7 @@ func (self *ChainManager) InsertChain(chain types.Blocks) error {
self.mu.Unlock() self.mu.Unlock()
self.eventMux.Post(NewBlockEvent{block}) self.eventMux.Post(NewBlockEvent{block})
self.eventMux.Post(messages)
} }
return nil return nil

View file

@ -33,7 +33,8 @@ func (self *Execution) Call(codeAddr []byte, caller vm.ContextRef) ([]byte, erro
func (self *Execution) exec(code, contextAddr []byte, caller vm.ContextRef) (ret []byte, err error) { func (self *Execution) exec(code, contextAddr []byte, caller vm.ContextRef) (ret []byte, err error) {
env := self.env env := self.env
evm := vm.NewVm(env) evm := vm.New(env)
if env.Depth() == vm.MaxCallDepth { if env.Depth() == vm.MaxCallDepth {
caller.ReturnGas(self.Gas, self.price) caller.ReturnGas(self.Gas, self.price)

View file

@ -34,7 +34,6 @@ type Filter struct {
topics [][]byte topics [][]byte
BlockCallback func(*types.Block) BlockCallback func(*types.Block)
PendingCallback func(*types.Block)
LogsCallback func(state.Logs) LogsCallback func(state.Logs)
} }
@ -129,30 +128,28 @@ func (self *Filter) Find() state.Logs {
return logs[skip:] return logs[skip:]
} }
func includes(addresses [][]byte, a []byte) bool { func includes(addresses [][]byte, a []byte) (found bool) {
for _, addr := range addresses { for _, addr := range addresses {
if !bytes.Equal(addr, a) { if bytes.Compare(addr, a) == 0 {
return false return true
} }
} }
return true return
} }
func (self *Filter) FilterLogs(logs state.Logs) state.Logs { func (self *Filter) FilterLogs(logs state.Logs) state.Logs {
var ret state.Logs var ret state.Logs
// Filter the logs for interesting stuff // Filter the logs for interesting stuff
Logs:
for _, log := range logs { for _, log := range logs {
if !bytes.Equal(self.address, log.Address()) { if !bytes.Equal(self.address, log.Address()) {
continue continue
} }
max := int(math.Min(float64(len(self.topics)), float64(len(log.Topics())))) for _, topic := range self.topics {
for i := 0; i < max; i++ { if !includes(log.Topics(), topic) {
if !bytes.Equal(log.Topics()[i], self.topics[i]) { continue
continue Logs
} }
} }

View file

@ -32,6 +32,7 @@ func GenesisBlock(db ethutil.Database) *types.Block {
genesis.SetReceipts(types.Receipts{}) genesis.SetReceipts(types.Receipts{})
statedb := state.New(genesis.Root(), db) statedb := state.New(genesis.Root(), db)
//statedb := state.New(genesis.Trie())
for _, addr := range []string{ for _, addr := range []string{
"dbdbdb2cbd23b783741e8d7fcf51e459b497e4a6", "dbdbdb2cbd23b783741e8d7fcf51e459b497e4a6",
"e4157b34ea9615cfbde6b4fda419828124b70c78", "e4157b34ea9615cfbde6b4fda419828124b70c78",

View file

@ -10,8 +10,6 @@ import (
"github.com/ethereum/go-ethereum/vm" "github.com/ethereum/go-ethereum/vm"
) )
const tryJit = false
/* /*
* The State transitioning model * The State transitioning model
* *
@ -186,7 +184,6 @@ func (self *StateTransition) TransitionState() (ret []byte, err error) {
return return
} }
//stateCopy := self.env.State().Copy()
vmenv := self.env vmenv := self.env
var ref vm.ContextRef var ref vm.ContextRef
if MessageCreatesContract(msg) { if MessageCreatesContract(msg) {
@ -199,34 +196,8 @@ func (self *StateTransition) TransitionState() (ret []byte, err error) {
ref.SetCode(ret) ref.SetCode(ret)
} }
} }
/*
if vmenv, ok := vmenv.(*VMEnv); ok && tryJit {
statelogger.Infof("CREATE: re-running using JIT (PH=%x)\n", stateCopy.Root()[:4])
// re-run using the JIT (validation for the JIT)
goodState := vmenv.State().Copy()
vmenv.state = stateCopy
vmenv.SetVmType(vm.JitVmTy)
vmenv.Create(sender, contract.Address(), self.msg.Data(), self.gas, self.gasPrice, self.value)
statelogger.Infof("DONE PH=%x STD_H=%x JIT_H=%x\n", stateCopy.Root()[:4], goodState.Root()[:4], vmenv.State().Root()[:4])
self.state.Set(goodState)
}
*/
} else { } else {
ret, err = vmenv.Call(self.From(), self.To().Address(), self.msg.Data(), self.gas, self.gasPrice, self.value) ret, err = vmenv.Call(self.From(), self.To().Address(), self.msg.Data(), self.gas, self.gasPrice, self.value)
/*
if vmenv, ok := vmenv.(*VMEnv); ok && tryJit {
statelogger.Infof("CALL: re-running using JIT (PH=%x)\n", stateCopy.Root()[:4])
// re-run using the JIT (validation for the JIT)
goodState := vmenv.State().Copy()
vmenv.state = stateCopy
vmenv.SetVmType(vm.JitVmTy)
vmenv.Call(self.From(), self.To().Address(), self.msg.Data(), self.gas, self.gasPrice, self.value)
statelogger.Infof("DONE PH=%x STD_H=%x JIT_H=%x\n", stateCopy.Root()[:4], goodState.Root()[:4], vmenv.State().Root()[:4])
self.state.Set(goodState)
}
*/
} }
if err != nil { if err != nil {

View file

@ -6,6 +6,7 @@ import (
"math/big" "math/big"
"sort" "sort"
"time" "time"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethutil" "github.com/ethereum/go-ethereum/ethutil"
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
@ -145,10 +146,6 @@ func (self *Block) SetTransactions(transactions Transactions) {
self.transactions = transactions self.transactions = transactions
self.header.TxHash = DeriveSha(transactions) self.header.TxHash = DeriveSha(transactions)
} }
func (self *Block) AddTransaction(transaction *Transaction) {
self.transactions = append(self.transactions, transaction)
self.SetTransactions(self.transactions)
}
func (self *Block) Receipts() Receipts { func (self *Block) Receipts() Receipts {
return self.receipts return self.receipts
@ -159,10 +156,6 @@ func (self *Block) SetReceipts(receipts Receipts) {
self.header.ReceiptHash = DeriveSha(receipts) self.header.ReceiptHash = DeriveSha(receipts)
self.header.Bloom = CreateBloom(receipts) self.header.Bloom = CreateBloom(receipts)
} }
func (self *Block) AddReceipt(receipt *Receipt) {
self.receipts = append(self.receipts, receipt)
self.SetReceipts(self.receipts)
}
func (self *Block) RlpData() interface{} { func (self *Block) RlpData() interface{} {
return []interface{}{self.header, self.transactions, self.uncles} return []interface{}{self.header, self.transactions, self.uncles}
@ -180,6 +173,9 @@ func (self *Block) Coinbase() []byte { return self.header.Coinbase }
func (self *Block) Time() int64 { return int64(self.header.Time) } func (self *Block) Time() int64 { return int64(self.header.Time) }
func (self *Block) GasLimit() *big.Int { return self.header.GasLimit } func (self *Block) GasLimit() *big.Int { return self.header.GasLimit }
func (self *Block) GasUsed() *big.Int { return self.header.GasUsed } func (self *Block) GasUsed() *big.Int { return self.header.GasUsed }
//func (self *Block) Trie() *ptrie.Trie { return ptrie.New(self.header.Root, ethutil.Config.Db) }
//func (self *Block) State() *state.StateDB { return state.New(self.Trie()) }
func (self *Block) Root() []byte { return self.header.Root } func (self *Block) Root() []byte { return self.header.Root }
func (self *Block) SetRoot(root []byte) { self.header.Root = root } func (self *Block) SetRoot(root []byte) { self.header.Root = root }
func (self *Block) Size() ethutil.StorageSize { return ethutil.StorageSize(len(ethutil.Encode(self))) } func (self *Block) Size() ethutil.StorageSize { return ethutil.StorageSize(len(ethutil.Encode(self))) }

View file

@ -1,7 +1,11 @@
package types package types
import "math/big" import (
"math/big"
"github.com/ethereum/go-ethereum/state"
)
type BlockProcessor interface { type BlockProcessor interface {
Process(*Block) (*big.Int, error) Process(*Block) (*big.Int, state.Messages, error)
} }

View file

@ -14,7 +14,6 @@ type VMEnv struct {
msg Message msg Message
depth int depth int
chain *ChainManager chain *ChainManager
typ vm.Type
} }
func NewEnv(state *state.StateDB, chain *ChainManager, msg Message, block *types.Block) *VMEnv { func NewEnv(state *state.StateDB, chain *ChainManager, msg Message, block *types.Block) *VMEnv {
@ -23,7 +22,6 @@ func NewEnv(state *state.StateDB, chain *ChainManager, msg Message, block *types
state: state, state: state,
block: block, block: block,
msg: msg, msg: msg,
typ: vm.StdVmTy,
} }
} }
@ -37,8 +35,6 @@ func (self *VMEnv) Value() *big.Int { return self.msg.Value() }
func (self *VMEnv) State() *state.StateDB { return self.state } func (self *VMEnv) State() *state.StateDB { return self.state }
func (self *VMEnv) Depth() int { return self.depth } func (self *VMEnv) Depth() int { return self.depth }
func (self *VMEnv) SetDepth(i int) { self.depth = i } func (self *VMEnv) SetDepth(i int) { self.depth = i }
func (self *VMEnv) VmType() vm.Type { return self.typ }
func (self *VMEnv) SetVmType(t vm.Type) { self.typ = t }
func (self *VMEnv) GetHash(n uint64) []byte { func (self *VMEnv) GetHash(n uint64) []byte {
if block := self.chain.GetBlockByNumber(n); block != nil { if block := self.chain.GetBlockByNumber(n); block != nil {
return block.Hash() return block.Hash()

View file

@ -17,6 +17,10 @@ import (
"github.com/ethereum/go-ethereum/whisper" "github.com/ethereum/go-ethereum/whisper"
) )
const (
seedNodeAddress = "poc-8.ethdev.com:30303"
)
type Config struct { type Config struct {
Name string Name string
Version string Version string
@ -137,13 +141,14 @@ func New(config *Config) (*Ethereum, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
fmt.Println(nat)
eth.net = &p2p.Server{ eth.net = &p2p.Server{
Identity: clientId, Identity: clientId,
MaxPeers: config.MaxPeers, MaxPeers: config.MaxPeers,
Protocols: protocols, Protocols: protocols,
Blacklist: eth.blacklist, Blacklist: eth.blacklist,
NAT: nat, NAT: p2p.UPNP(),
NoDial: !config.Dial, NoDial: !config.Dial,
} }
@ -219,7 +224,7 @@ func (s *Ethereum) Coinbase() []byte {
} }
// Start the ethereum // Start the ethereum
func (s *Ethereum) Start(seedNode string) error { func (s *Ethereum) Start(seed bool) error {
err := s.net.Start() err := s.net.Start()
if err != nil { if err != nil {
return err return err
@ -242,9 +247,9 @@ func (s *Ethereum) Start(seedNode string) error {
go s.blockBroadcastLoop() go s.blockBroadcastLoop()
// TODO: read peers here // TODO: read peers here
if len(seedNode) > 0 { if seed {
logger.Infof("Connect to seed node %v", seedNode) logger.Infof("Connect to seed node %v", seedNodeAddress)
if err := s.SuggestPeer(seedNode); err != nil { if err := s.SuggestPeer(seedNodeAddress); err != nil {
logger.Infoln(err) logger.Infoln(err)
} }
} }

View file

@ -636,12 +636,12 @@ func (self *BlockPool) AddBlock(block *types.Block, peerId string) {
// validate block for PoW // validate block for PoW
if !self.verifyPoW(block) { if !self.verifyPoW(block) {
poolLogger.Warnf("invalid pow on block [%s %v] by peer %s", name(hash), block.Number(), peerId) poolLogger.Warnf("invalid pow on block [%s] by peer %s", name(hash), peerId)
self.peerError(peerId, ErrInvalidPoW, "%x", hash) self.peerError(peerId, ErrInvalidPoW, "%x", hash)
return return
} }
} }
poolLogger.DebugDetailf("added block [%s] sent by peer %s", name(hash), peerId) poolLogger.Debugf("added block [%s] sent by peer %s", name(hash), peerId)
node.block = block node.block = block
node.blockBy = peerId node.blockBy = peerId

View file

@ -46,7 +46,6 @@ type ethProtocol struct {
// used as an argument to EthProtocol // used as an argument to EthProtocol
type txPool interface { type txPool interface {
AddTransactions([]*types.Transaction) AddTransactions([]*types.Transaction)
GetTransactions() types.Transactions
} }
type chainManager interface { type chainManager interface {
@ -102,7 +101,6 @@ func runEthProtocol(txPool txPool, chainManager chainManager, blockPool blockPoo
} }
err = self.handleStatus() err = self.handleStatus()
if err == nil { if err == nil {
self.propagateTxs()
for { for {
err = self.handle() err = self.handle()
if err != nil { if err != nil {
@ -326,13 +324,3 @@ func (self *ethProtocol) protoErrorDisconnect(code int, format string, params ..
} }
} }
func (self *ethProtocol) propagateTxs() {
transactions := self.txPool.GetTransactions()
iface := make([]interface{}, len(transactions))
for i, transaction := range transactions {
iface[i] = transaction
}
self.rw.WriteMsg(p2p.NewMsg(TxMsg, iface...))
}

View file

@ -80,8 +80,6 @@ func (self *testTxPool) AddTransactions(txs []*types.Transaction) {
} }
} }
func (self *testTxPool) GetTransactions() types.Transactions { return nil }
func (self *testChainManager) GetBlockHashesFromHash(hash []byte, amount uint64) (hashes [][]byte) { func (self *testChainManager) GetBlockHashesFromHash(hash []byte, amount uint64) (hashes [][]byte) {
if self.getBlockHashes != nil { if self.getBlockHashes != nil {
hashes = self.getBlockHashes(hash, amount) hashes = self.getBlockHashes(hash, amount)

View file

@ -60,7 +60,7 @@ func (self *FilterManager) GetFilter(id int) *core.Filter {
func (self *FilterManager) filterLoop() { func (self *FilterManager) filterLoop() {
// Subscribe to events // Subscribe to events
events := self.eventMux.Subscribe(core.PendingBlockEvent{}, core.NewBlockEvent{}, state.Logs(nil)) events := self.eventMux.Subscribe(core.NewBlockEvent{}, state.Messages(nil))
out: out:
for { for {
@ -78,15 +78,6 @@ out:
} }
self.filterMu.RUnlock() self.filterMu.RUnlock()
case core.PendingBlockEvent:
self.filterMu.RLock()
for _, filter := range self.filters {
if filter.PendingCallback != nil {
filter.PendingCallback(event.Block)
}
}
self.filterMu.RUnlock()
case state.Logs: case state.Logs:
self.filterMu.RLock() self.filterMu.RLock()
for _, filter := range self.filters { for _, filter := range self.filters {

View file

@ -27,3 +27,6 @@ done
go tool cover -func profile.cov go tool cover -func profile.cov
# To submit the test coverage result to coveralls.io,
# use goveralls (https://github.com/mattn/goveralls)
goveralls -coverprofile=profile.cov -service=travis-ci -repotoken $COVERALLS_TOKEN

View file

@ -184,7 +184,9 @@ func (self *Miner) mine() {
block.Header().Extra = self.Extra block.Header().Extra = self.Extra
// Apply uncles // Apply uncles
if len(self.uncles) > 0 {
block.SetUncles(self.uncles) block.SetUncles(self.uncles)
}
parent := chainMan.GetBlock(block.ParentHash()) parent := chainMan.GetBlock(block.ParentHash())
coinbase := state.GetOrNewStateObject(block.Coinbase()) coinbase := state.GetOrNewStateObject(block.Coinbase())
@ -204,7 +206,7 @@ func (self *Miner) mine() {
block.SetReceipts(receipts) block.SetReceipts(receipts)
// Accumulate the rewards included for this block // Accumulate the rewards included for this block
blockProcessor.AccumulateRewards(state, block, parent) blockProcessor.AccumelateRewards(state, block, parent)
state.Update(ethutil.Big0) state.Update(ethutil.Big0)
block.SetRoot(state.Root()) block.SetRoot(state.Root())

View file

@ -1,169 +0,0 @@
package miner
import (
"fmt"
"math/big"
"sort"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/eth"
"github.com/ethereum/go-ethereum/ethutil"
"github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/pow"
"github.com/ethereum/go-ethereum/state"
"gopkg.in/fatih/set.v0"
)
type environment struct {
totalUsedGas *big.Int
state *state.StateDB
coinbase *state.StateObject
block *types.Block
ancestors *set.Set
uncles *set.Set
}
func env(block *types.Block, eth *eth.Ethereum) *environment {
state := state.New(block.Root(), eth.Db())
env := &environment{
totalUsedGas: new(big.Int),
state: state,
block: block,
ancestors: set.New(),
uncles: set.New(),
coinbase: state.GetOrNewStateObject(block.Coinbase()),
}
for _, ancestor := range eth.ChainManager().GetAncestors(block, 7) {
env.ancestors.Add(string(ancestor.Hash()))
}
return env
}
type Agent interface {
Comms() chan<- *types.Block
}
type worker struct {
agents []chan<- *types.Block
mux *event.TypeMux
quit chan struct{}
pow pow.PoW
eth *eth.Ethereum
chain *core.ChainManager
proc *core.BlockProcessor
coinbase []byte
current *environment
}
func (self *worker) register(agent chan<- *types.Block) {
self.agents = append(self.agents, agent)
}
func (self *worker) update() {
events := self.mux.Subscribe(core.NewBlockEvent{}, core.TxPreEvent{}, &LocalTx{})
out:
for {
select {
case event := <-events.Chan():
switch event := event.(type) {
case core.NewBlockEvent:
if self.eth.ChainManager().HasBlock(event.Block.Hash()) {
}
case core.TxPreEvent:
if err := self.commitTransaction(event.Tx); err != nil {
self.commit()
}
}
case <-self.quit:
break out
}
}
}
func (self *worker) commit() {
self.current.state.Update(ethutil.Big0)
self.current.block.SetRoot(self.current.state.Root())
for _, agent := range self.agents {
agent <- self.current.block
}
}
func (self *worker) commitNewWork() {
self.current = env(self.chain.NewBlock(self.coinbase), self.eth)
parent := self.chain.GetBlock(self.current.block.ParentHash())
self.current.coinbase.SetGasPool(core.CalcGasLimit(parent, self.current.block))
transactions := self.eth.TxPool().GetTransactions()
sort.Sort(types.TxByNonce{transactions})
// Keep track of transactions which return errors so they can be removed
var remove types.Transactions
for _, tx := range transactions {
err := self.commitTransaction(tx)
switch {
case core.IsNonceErr(err):
remove = append(remove, tx)
case core.IsGasLimitErr(err):
// ignore
default:
minerlogger.Infoln(err)
remove = append(remove, tx)
}
}
self.eth.TxPool().RemoveSet(remove)
self.current.coinbase.AddAmount(core.BlockReward)
self.commit()
}
var (
inclusionReward = new(big.Int).Div(core.BlockReward, big.NewInt(32))
_uncleReward = new(big.Int).Mul(core.BlockReward, big.NewInt(15))
uncleReward = new(big.Int).Div(_uncleReward, big.NewInt(16))
)
func (self *worker) commitUncle(uncle *types.Header) error {
if self.current.uncles.Has(string(uncle.Hash())) {
// Error not unique
return core.UncleError("Uncle not unique")
}
self.current.uncles.Add(string(uncle.Hash()))
if !self.current.ancestors.Has(string(uncle.ParentHash)) {
return core.UncleError(fmt.Sprintf("Uncle's parent unknown (%x)", uncle.ParentHash[0:4]))
}
if !self.pow.Verify(types.NewBlockWithHeader(uncle)) {
return core.ValidationError("Uncle's nonce is invalid (= %v)", ethutil.Bytes2Hex(uncle.Nonce))
}
uncleAccount := self.current.state.GetAccount(uncle.Coinbase)
uncleAccount.AddAmount(uncleReward)
self.current.coinbase.AddBalance(uncleReward)
return nil
}
func (self *worker) commitTransaction(tx *types.Transaction) error {
snapshot := self.current.state.Copy()
receipt, txGas, err := self.proc.ApplyTransaction(self.current.coinbase, self.current.state, self.current.block, tx, self.current.totalUsedGas, true)
if err != nil {
self.current.state.Set(snapshot)
return err
}
self.current.totalUsedGas.Add(self.current.totalUsedGas, txGas)
self.current.block.AddTransaction(tx)
self.current.block.AddReceipt(receipt)
return nil
}

View file

@ -53,6 +53,7 @@ func (pow *EasyPow) Search(block pow.Block, stop <-chan struct{}) []byte {
elapsed := time.Now().UnixNano() - start elapsed := time.Now().UnixNano() - start
hashes := ((float64(1e9) / float64(elapsed)) * float64(i)) / 1000 hashes := ((float64(1e9) / float64(elapsed)) * float64(i)) / 1000
pow.HashRate = int64(hashes) pow.HashRate = int64(hashes)
powlogger.Infoln("Hashing @", pow.HashRate, "khash")
t = time.Now() t = time.Now()
} }
@ -82,7 +83,7 @@ func verify(hash []byte, diff *big.Int, nonce []byte) bool {
sha.Write(d) sha.Write(d)
verification := new(big.Int).Div(ethutil.BigPow(2, 256), diff) verification := new(big.Int).Div(ethutil.BigPow(2, 256), diff)
res := ethutil.BigD(sha.Sum(nil)) res := ethutil.U256(ethutil.BigD(sha.Sum(nil)))
return res.Cmp(verification) <= 0 return res.Cmp(verification) <= 0
} }

View file

@ -37,6 +37,16 @@ type NewTxArgs struct {
Data string `json:"data"` Data string `json:"data"`
} }
func (a *NewTxArgs) requirements() error {
if a.Gas == "" {
return NewErrorResponse("Transact requires a 'gas' value as argument")
}
if a.GasPrice == "" {
return NewErrorResponse("Transact requires a 'gasprice' value as argument")
}
return nil
}
type PushTxArgs struct { type PushTxArgs struct {
Tx string `json:"tx"` Tx string `json:"tx"`
} }
@ -204,7 +214,7 @@ type FilterOptions struct {
Earliest int64 Earliest int64
Latest int64 Latest int64
Address string Address string
Topic []string Topics []string
Skip int Skip int
Max int Max int
} }
@ -214,8 +224,8 @@ func toFilterOptions(options *FilterOptions) core.FilterOptions {
opts.Earliest = options.Earliest opts.Earliest = options.Earliest
opts.Latest = options.Latest opts.Latest = options.Latest
opts.Address = fromHex(options.Address) opts.Address = fromHex(options.Address)
opts.Topics = make([][]byte, len(options.Topic)) opts.Topics = make([][]byte, len(options.Topics))
for i, topic := range options.Topic { for i, topic := range options.Topics {
opts.Topics[i] = fromHex(topic) opts.Topics[i] = fromHex(topic)
} }

View file

@ -33,29 +33,30 @@ const (
ErrorDecodeArgs = "Error: Could not decode arguments" ErrorDecodeArgs = "Error: Could not decode arguments"
) )
type RpcRequest struct { type ErrorResponse struct {
JsonRpc string `json:"jsonrpc"` Error bool `json:"error"`
ID int `json:"id"` ErrorText string `json:"errorText"`
Method string `json:"method"`
Params []json.RawMessage `json:"params"`
} }
type RpcSuccessResponse struct { type RpcSuccessResponse struct {
ID int `json:"id"` ID int `json:"id"`
JsonRpc string `json:"jsonrpc"` JsonRpc string `json:"jsonrpc"`
Error bool `json:"error"`
Result interface{} `json:"result"` Result interface{} `json:"result"`
} }
type RpcErrorResponse struct { type RpcErrorResponse struct {
ID *int `json:"id"` ID int `json:"id"`
JsonRpc string `json:"jsonrpc"` JsonRpc string `json:"jsonrpc"`
Error *RpcErrorObject `json:"error"` Error bool `json:"error"`
ErrorText string `json:"errortext"`
} }
type RpcErrorObject struct { type RpcRequest struct {
Code int `json:"code"` JsonRpc string `json:"jsonrpc"`
Message string `json:"message"` ID int `json:"id"`
// Data interface{} `json:"data"` Method string `json:"method"`
Params []json.RawMessage `json:"params"`
} }
func NewErrorResponse(msg string) error { func NewErrorResponse(msg string) error {
@ -216,21 +217,6 @@ func (req *RpcRequest) ToFilterArgs() (*FilterOptions, error) {
return args, nil return args, nil
} }
func (req *RpcRequest) ToFilterStringArgs() (string, error) {
if len(req.Params) < 1 {
return "", NewErrorResponse(ErrorArguments)
}
var args string
err := json.Unmarshal(req.Params[0], &args)
if err != nil {
return "", NewErrorResponse(ErrorDecodeArgs)
}
rpclogger.DebugDetailf("%T %v", args, args)
return args, nil
}
func (req *RpcRequest) ToFilterChangedArgs() (int, error) { func (req *RpcRequest) ToFilterChangedArgs() (int, error) {
if len(req.Params) < 1 { if len(req.Params) < 1 {
return 0, NewErrorResponse(ErrorArguments) return 0, NewErrorResponse(ErrorArguments)

View file

@ -32,7 +32,6 @@ import (
"sync" "sync"
"github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/ethutil" "github.com/ethereum/go-ethereum/ethutil"
@ -41,11 +40,6 @@ import (
"github.com/ethereum/go-ethereum/xeth" "github.com/ethereum/go-ethereum/xeth"
) )
const (
defaultGasPrice = "10000000000000"
defaultGas = "10000"
)
type EthereumApi struct { type EthereumApi struct {
xeth *xeth.XEth xeth *xeth.XEth
filterManager *filter.FilterManager filterManager *filter.FilterManager
@ -76,7 +70,6 @@ func NewEthereumApi(eth *xeth.XEth) *EthereumApi {
func (self *EthereumApi) NewFilter(args *FilterOptions, reply *interface{}) error { func (self *EthereumApi) NewFilter(args *FilterOptions, reply *interface{}) error {
var id int var id int
filter := core.NewFilter(self.xeth.Backend()) filter := core.NewFilter(self.xeth.Backend())
filter.SetOptions(toFilterOptions(args))
filter.LogsCallback = func(logs state.Logs) { filter.LogsCallback = func(logs state.Logs) {
self.logMut.Lock() self.logMut.Lock()
defer self.logMut.Unlock() defer self.logMut.Unlock()
@ -89,25 +82,6 @@ func (self *EthereumApi) NewFilter(args *FilterOptions, reply *interface{}) erro
return nil return nil
} }
func (self *EthereumApi) NewFilterString(args string, reply *interface{}) error {
var id int
filter := core.NewFilter(self.xeth.Backend())
callback := func(block *types.Block) {
self.logs[id] = append(self.logs[id], &state.StateLog{})
}
if args == "pending" {
filter.PendingCallback = callback
} else if args == "chain" {
filter.BlockCallback = callback
}
id = self.filterManager.InstallFilter(filter)
*reply = id
return nil
}
func (self *EthereumApi) FilterChanged(id int, reply *interface{}) error { func (self *EthereumApi) FilterChanged(id int, reply *interface{}) error {
self.logMut.RLock() self.logMut.RLock()
defer self.logMut.RUnlock() defer self.logMut.RUnlock()
@ -141,14 +115,10 @@ func (p *EthereumApi) GetBlock(args *GetBlockArgs, reply *interface{}) error {
} }
func (p *EthereumApi) Transact(args *NewTxArgs, reply *interface{}) error { func (p *EthereumApi) Transact(args *NewTxArgs, reply *interface{}) error {
if len(args.Gas) == 0 { err := args.requirements()
args.Gas = defaultGas if err != nil {
return err
} }
if len(args.GasPrice) == 0 {
args.GasPrice = defaultGasPrice
}
result, _ := p.xeth.Transact( /* TODO specify account */ args.To, args.Value, args.Gas, args.GasPrice, args.Data) result, _ := p.xeth.Transact( /* TODO specify account */ args.To, args.Value, args.Gas, args.GasPrice, args.Data)
*reply = result *reply = result
return nil return nil
@ -409,12 +379,6 @@ func (p *EthereumApi) GetRequestReply(req *RpcRequest, reply *interface{}) error
return err return err
} }
return p.NewFilter(args, reply) return p.NewFilter(args, reply)
case "eth_newFilterString":
args, err := req.ToFilterStringArgs()
if err != nil {
return err
}
return p.NewFilterString(args, reply)
case "eth_changed": case "eth_changed":
args, err := req.ToFilterChangedArgs() args, err := req.ToFilterChangedArgs()
if err != nil { if err != nil {
@ -422,7 +386,7 @@ func (p *EthereumApi) GetRequestReply(req *RpcRequest, reply *interface{}) error
} }
return p.FilterChanged(args, reply) return p.FilterChanged(args, reply)
case "eth_gasPrice": case "eth_gasPrice":
*reply = defaultGasPrice *reply = "10000000000000"
return nil return nil
case "web3_sha3": case "web3_sha3":
args, err := req.ToSha3Args() args, err := req.ToSha3Args()

View file

@ -18,11 +18,10 @@ package rpc
import ( import (
"encoding/json" "encoding/json"
"github.com/ethereum/go-ethereum/logger"
"io" "io"
"net/http" "net/http"
"github.com/ethereum/go-ethereum/ethutil" "github.com/ethereum/go-ethereum/ethutil"
"github.com/ethereum/go-ethereum/logger"
"github.com/ethereum/go-ethereum/state" "github.com/ethereum/go-ethereum/state"
) )
@ -37,7 +36,7 @@ func (self JsonWrapper) Send(writer io.Writer, v interface{}) (n int, err error)
rpclogger.Fatalln("Error marshalling JSON", err) rpclogger.Fatalln("Error marshalling JSON", err)
return 0, err return 0, err
} }
rpclogger.DebugDetailf("Sending payload: %s", payload) rpclogger.Infof("Sending payload: %s", payload)
return writer.Write(payload) return writer.Write(payload)
} }

View file

@ -22,30 +22,35 @@ import (
"net/http" "net/http"
"code.google.com/p/go.net/websocket" "code.google.com/p/go.net/websocket"
"github.com/ethereum/go-ethereum/eth"
"github.com/ethereum/go-ethereum/event/filter"
"github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/logger"
"github.com/ethereum/go-ethereum/rpc" "github.com/ethereum/go-ethereum/rpc"
"github.com/ethereum/go-ethereum/xeth" "github.com/ethereum/go-ethereum/xeth"
) )
var wslogger = logger.NewLogger("RPC-WS") var wslogger = logger.NewLogger("RPC-WS")
var JSON rpc.JsonWrapper
type WebSocketServer struct { type WebSocketServer struct {
pipe *xeth.XEth eth *eth.Ethereum
filterManager *filter.FilterManager
port int port int
doneCh chan bool doneCh chan bool
listener net.Listener listener net.Listener
} }
func NewWebSocketServer(pipe *xeth.XEth, port int) (*WebSocketServer, error) { func NewWebSocketServer(eth *eth.Ethereum, port int) (*WebSocketServer, error) {
sport := fmt.Sprintf(":%d", port) sport := fmt.Sprintf(":%d", port)
l, err := net.Listen("tcp", sport) l, err := net.Listen("tcp", sport)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &WebSocketServer{ filterManager := filter.NewFilterManager(eth.EventMux())
pipe, go filterManager.Start()
return &WebSocketServer{eth,
filterManager,
port, port,
make(chan bool), make(chan bool),
l, l,
@ -70,7 +75,7 @@ func (self *WebSocketServer) Start() {
wslogger.Infof("Starting RPC-WS server on port %d", self.port) wslogger.Infof("Starting RPC-WS server on port %d", self.port)
go self.handlerLoop() go self.handlerLoop()
api := rpc.NewEthereumApi(self.pipe) api := rpc.NewEthereumApi(xeth.New(self.eth))
h := self.apiHandler(api) h := self.apiHandler(api)
http.Handle("/ws", h) http.Handle("/ws", h)
@ -91,29 +96,27 @@ func (s *WebSocketServer) apiHandler(api *rpc.EthereumApi) http.Handler {
} }
func sockHandler(api *rpc.EthereumApi) websocket.Handler { func sockHandler(api *rpc.EthereumApi) websocket.Handler {
var jsonrpcver string = "2.0"
fn := func(conn *websocket.Conn) { fn := func(conn *websocket.Conn) {
for { for {
wslogger.Debugln("Handling request") wslogger.Debugln("Handling request")
var reqParsed rpc.RpcRequest var reqParsed rpc.RpcRequest
if err := websocket.JSON.Receive(conn, &reqParsed); err != nil { if err := websocket.JSON.Receive(conn, &reqParsed); err != nil {
jsonerr := &rpc.RpcErrorObject{-32700, rpc.ErrorParseRequest} wslogger.Debugln(rpc.ErrorParseRequest)
JSON.Send(conn, &rpc.RpcErrorResponse{JsonRpc: jsonrpcver, ID: nil, Error: jsonerr}) websocket.JSON.Send(conn, rpc.RpcErrorResponse{JsonRpc: reqParsed.JsonRpc, ID: reqParsed.ID, Error: true, ErrorText: rpc.ErrorParseRequest})
continue continue
} }
var response interface{} var response interface{}
reserr := api.GetRequestReply(&reqParsed, &response) reserr := api.GetRequestReply(&reqParsed, &response)
if reserr != nil { if reserr != nil {
wslogger.Warnln(reserr) wslogger.Errorln(reserr)
jsonerr := &rpc.RpcErrorObject{-32603, reserr.Error()} websocket.JSON.Send(conn, rpc.RpcErrorResponse{JsonRpc: reqParsed.JsonRpc, ID: reqParsed.ID, Error: true, ErrorText: reserr.Error()})
JSON.Send(conn, &rpc.RpcErrorResponse{JsonRpc: jsonrpcver, ID: &reqParsed.ID, Error: jsonerr})
continue continue
} }
wslogger.Debugf("Generated response: %T %s", response, response) wslogger.Debugf("Generated response: %T %s", response, response)
JSON.Send(conn, &rpc.RpcSuccessResponse{JsonRpc: jsonrpcver, ID: reqParsed.ID, Result: response}) websocket.JSON.Send(conn, rpc.RpcSuccessResponse{JsonRpc: reqParsed.JsonRpc, ID: reqParsed.ID, Error: false, Result: response})
} }
} }
return websocket.Handler(fn) return websocket.Handler(fn)

View file

@ -31,7 +31,7 @@ type StateDB struct {
// Create a new state from a given trie // Create a new state from a given trie
func New(root []byte, db ethutil.Database) *StateDB { func New(root []byte, db ethutil.Database) *StateDB {
trie := trie.New(ethutil.CopyBytes(root), db) trie := trie.New(root, db)
return &StateDB{db: db, trie: trie, stateObjects: make(map[string]*StateObject), manifest: NewManifest(), refund: make(map[string]*big.Int)} return &StateDB{db: db, trie: trie, stateObjects: make(map[string]*StateObject), manifest: NewManifest(), refund: make(map[string]*big.Int)}
} }
@ -234,9 +234,12 @@ func (self *StateDB) Copy() *StateDB {
} }
func (self *StateDB) Set(state *StateDB) { func (self *StateDB) Set(state *StateDB) {
if state == nil {
panic("Tried setting 'state' to nil through 'Set'")
}
self.trie = state.trie self.trie = state.trie
self.stateObjects = state.stateObjects self.stateObjects = state.stateObjects
self.refund = state.refund self.refund = state.refund
self.logs = state.logs self.logs = state.logs
} }

View file

@ -1,6 +1,4 @@
venv/ venv/
*~ *~
*.swp *.swp
*.swo
.vagrant/ .vagrant/
client-tests.pem

View file

@ -1,8 +1,8 @@
{ {
"genesis_rlp_hex": "f9012ef90129a00000000000000000000000000000000000000000000000000000000000000000a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347940000000000000000000000000000000000000000a0156df8ef53c723b40f97aff55dd785489cae8b457495916147687746bd5ee077a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b840000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008302000080830f4240808080a004994f67dc55b09e814ab7ffc8df3686b4afb2bb53e60eae97ef043fe03fb829c0c0", "genesis_rlp_hex": "f9012ef90129a00000000000000000000000000000000000000000000000000000000000000000a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347940000000000000000000000000000000000000000a0c67c70f5d7d3049337d1dcc0503a249881120019a8e7322774dbfe57b463718ca056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b840000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008302000080830f4240808080a004994f67dc55b09e814ab7ffc8df3686b4afb2bb53e60eae97ef043fe03fb829c0c0",
"genesis_state_root": "156df8ef53c723b40f97aff55dd785489cae8b457495916147687746bd5ee077", "genesis_state_root": "c67c70f5d7d3049337d1dcc0503a249881120019a8e7322774dbfe57b463718c",
"initial_alloc": { "initial_alloc": {
"dbdbdb2cbd23b783741e8d7fcf51e459b497e4a6": "1606938044258990275541962092341162602522202993782792835301376", "51ba59315b3a95761d0863b05ccc7a7f54703d99": "1606938044258990275541962092341162602522202993782792835301376",
"e4157b34ea9615cfbde6b4fda419828124b70c78": "1606938044258990275541962092341162602522202993782792835301376", "e4157b34ea9615cfbde6b4fda419828124b70c78": "1606938044258990275541962092341162602522202993782792835301376",
"b9c015918bdaba24b4ff057a92a3873d6eb201be": "1606938044258990275541962092341162602522202993782792835301376", "b9c015918bdaba24b4ff057a92a3873d6eb201be": "1606938044258990275541962092341162602522202993782792835301376",
"6c386a4b26f73c802f34673f7248bb118f97424a": "1606938044258990275541962092341162602522202993782792835301376", "6c386a4b26f73c802f34673f7248bb118f97424a": "1606938044258990275541962092341162602522202993782792835301376",
@ -11,5 +11,5 @@
"e6716f9544a56c530d868e4bfbacb172315bdead": "1606938044258990275541962092341162602522202993782792835301376", "e6716f9544a56c530d868e4bfbacb172315bdead": "1606938044258990275541962092341162602522202993782792835301376",
"1a26338f0d905e295fccb71fa9ea849ffa12aaf4": "1606938044258990275541962092341162602522202993782792835301376" "1a26338f0d905e295fccb71fa9ea849ffa12aaf4": "1606938044258990275541962092341162602522202993782792835301376"
}, },
"genesis_hash": "c9cb614fddd89b3bc6e2f0ed1f8e58e8a0d826612a607a6151be6f39c991a941" "genesis_hash": "779b1b620b03c0fb24963e183d5e88e3dbe4484e3f6e2aa05942e3be7b48e179"
} }

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,44 +1,4 @@
{ {
"RefundOverflow" : {
"env" : {
"currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
"currentDifficulty" : "45678256",
"currentGasLimit" : "115792089237316195423570985008687907853269984665640564039457584007913129639935",
"currentNumber" : "0",
"currentTimestamp" : 1,
"previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6"
},
"logs" : [
],
"out" : "0x",
"post" : {
"a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"balance" : "400",
"code" : "0x",
"nonce" : "0",
"storage" : {
}
}
},
"pre" : {
"a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"balance" : "400",
"code" : "0x",
"nonce" : "0",
"storage" : {
}
}
},
"transaction" : {
"data" : "",
"gasLimit" : "5789604461865809771178549250434395392663499233282028201972879200395656482016",
"gasPrice" : "20",
"nonce" : "0",
"secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8",
"to" : "b94f5374fce5edbc8e2a8697c15331677e6ebf0b",
"value" : ""
}
},
"refund500" : { "refund500" : {
"env" : { "env" : {
"currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",

View file

@ -1,44 +1,4 @@
{ {
"OverflowGasMakeMoney" : {
"env" : {
"currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
"currentDifficulty" : "45678256",
"currentGasLimit" : "115792089237316195423570985008687907853269984665640564039457584007913129639935",
"currentNumber" : "0",
"currentTimestamp" : 1,
"previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6"
},
"logs" : [
],
"out" : "0x",
"post" : {
"a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"balance" : "1000",
"code" : "0x",
"nonce" : "0",
"storage" : {
}
}
},
"pre" : {
"a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"balance" : "1000",
"code" : "0x",
"nonce" : "0",
"storage" : {
}
}
},
"transaction" : {
"data" : "",
"gasLimit" : "115792089237316195423570985008687907853269984665640564039457584007913129639435",
"gasPrice" : "1",
"nonce" : "0",
"secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8",
"to" : "b94f5374fce5edbc8e2a8697c15331677e6ebf0b",
"value" : "501"
}
},
"makeMoney" : { "makeMoney" : {
"env" : { "env" : {
"currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",

View file

@ -191,256 +191,6 @@
"value" : "" "value" : ""
} }
}, },
"InternlCallStoreClearsOOG" : {
"env" : {
"currentCoinbase" : "b94f5374fce5edbc8e2a8697c15331677e6ebf0b",
"currentDifficulty" : "45678256",
"currentGasLimit" : "10000",
"currentNumber" : "0",
"currentTimestamp" : 1,
"previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6"
},
"logs" : [
],
"out" : "0x",
"post" : {
"0000000000000000000000000000000000000000" : {
"balance" : "1",
"code" : "0x6000600055600060015560006002556000600355600060045560006005556000600655600060075560006008556000600955",
"nonce" : "0",
"storage" : {
"0x" : "0x0c",
"0x01" : "0x0c",
"0x02" : "0x0c",
"0x03" : "0x0c",
"0x04" : "0x0c",
"0x05" : "0x0c",
"0x06" : "0x0c",
"0x07" : "0x0c",
"0x08" : "0x0c",
"0x09" : "0x0c"
}
},
"a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"balance" : "6444",
"code" : "0x",
"nonce" : "1",
"storage" : {
}
},
"b94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"balance" : "546",
"code" : "0x",
"nonce" : "0",
"storage" : {
}
},
"c94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"balance" : "19",
"code" : "0x6000600060006000600160006013f1",
"nonce" : "0",
"storage" : {
}
}
},
"pre" : {
"0000000000000000000000000000000000000000" : {
"balance" : "0",
"code" : "0x6000600055600060015560006002556000600355600060045560006005556000600655600060075560006008556000600955",
"nonce" : "0",
"storage" : {
"0x" : "0x0c",
"0x01" : "0x0c",
"0x02" : "0x0c",
"0x03" : "0x0c",
"0x04" : "0x0c",
"0x05" : "0x0c",
"0x06" : "0x0c",
"0x07" : "0x0c",
"0x08" : "0x0c",
"0x09" : "0x0c"
}
},
"a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"balance" : "7000",
"code" : "0x",
"nonce" : "0",
"storage" : {
}
},
"c94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"balance" : "10",
"code" : "0x6000600060006000600160006013f1",
"nonce" : "0",
"storage" : {
}
}
},
"transaction" : {
"data" : "",
"gasLimit" : "700",
"gasPrice" : "1",
"nonce" : "",
"secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8",
"to" : "c94f5374fce5edbc8e2a8697c15331677e6ebf0b",
"value" : "10"
}
},
"StoreClearsAndInternlCallStoreClearsOOG" : {
"env" : {
"currentCoinbase" : "b94f5374fce5edbc8e2a8697c15331677e6ebf0b",
"currentDifficulty" : "45678256",
"currentGasLimit" : "10000",
"currentNumber" : "0",
"currentTimestamp" : 1,
"previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6"
},
"logs" : [
],
"out" : "0x",
"post" : {
"0000000000000000000000000000000000000000" : {
"balance" : "1",
"code" : "0x6000600055600060015560006002556000600355600060045560006005556000600655600060075560006008556000600955",
"nonce" : "0",
"storage" : {
"0x" : "0x0c",
"0x01" : "0x0c",
"0x02" : "0x0c",
"0x03" : "0x0c",
"0x04" : "0x0c",
"0x05" : "0x0c",
"0x06" : "0x0c",
"0x07" : "0x0c",
"0x08" : "0x0c",
"0x09" : "0x0c"
}
},
"a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"balance" : "6713",
"code" : "0x",
"nonce" : "1",
"storage" : {
}
},
"b94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"balance" : "277",
"code" : "0x",
"nonce" : "0",
"storage" : {
}
},
"c94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"balance" : "19",
"code" : "0x60006000556000600155600060025560006003556000600060006000600160006013f1",
"nonce" : "0",
"storage" : {
"0x04" : "0x0c"
}
}
},
"pre" : {
"0000000000000000000000000000000000000000" : {
"balance" : "0",
"code" : "0x6000600055600060015560006002556000600355600060045560006005556000600655600060075560006008556000600955",
"nonce" : "0",
"storage" : {
"0x" : "0x0c",
"0x01" : "0x0c",
"0x02" : "0x0c",
"0x03" : "0x0c",
"0x04" : "0x0c",
"0x05" : "0x0c",
"0x06" : "0x0c",
"0x07" : "0x0c",
"0x08" : "0x0c",
"0x09" : "0x0c"
}
},
"a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"balance" : "7000",
"code" : "0x",
"nonce" : "0",
"storage" : {
}
},
"c94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"balance" : "10",
"code" : "0x60006000556000600155600060025560006003556000600060006000600160006013f1",
"nonce" : "0",
"storage" : {
"0x" : "0x0c",
"0x01" : "0x0c",
"0x02" : "0x0c",
"0x03" : "0x0c",
"0x04" : "0x0c"
}
}
},
"transaction" : {
"data" : "",
"gasLimit" : "700",
"gasPrice" : "1",
"nonce" : "",
"secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8",
"to" : "c94f5374fce5edbc8e2a8697c15331677e6ebf0b",
"value" : "10"
}
},
"TransactionCosts555" : {
"env" : {
"currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
"currentDifficulty" : "45678256",
"currentGasLimit" : "1000000",
"currentNumber" : "0",
"currentTimestamp" : 1,
"previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6"
},
"logs" : [
],
"out" : "0x",
"post" : {
"2adc25665018aa1fe0e6bc666dac8fc2697ff9ba" : {
"balance" : "555",
"code" : "0x",
"nonce" : "0",
"storage" : {
}
},
"a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"balance" : "99445",
"code" : "0x",
"nonce" : "1",
"storage" : {
}
},
"b94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"balance" : "0",
"code" : "0x",
"nonce" : "0",
"storage" : {
}
}
},
"pre" : {
"a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"balance" : "100000",
"code" : "0x",
"nonce" : "0",
"storage" : {
}
}
},
"transaction" : {
"data" : "0x00000000000000000000112233445566778f32",
"gasLimit" : "1000",
"gasPrice" : "1",
"nonce" : "0",
"secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8",
"to" : "b94f5374fce5edbc8e2a8697c15331677e6ebf0b",
"value" : "0"
}
},
"TransactionFromCoinbaseNotEnoughFounds" : { "TransactionFromCoinbaseNotEnoughFounds" : {
"env" : { "env" : {
"currentCoinbase" : "a94f5374fce5edbc8e2a8697c15331677e6ebf0b", "currentCoinbase" : "a94f5374fce5edbc8e2a8697c15331677e6ebf0b",
@ -481,86 +231,6 @@
"value" : "502" "value" : "502"
} }
}, },
"TransactionNonceCheck" : {
"env" : {
"currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
"currentDifficulty" : "45678256",
"currentGasLimit" : "1000000",
"currentNumber" : "0",
"currentTimestamp" : 1,
"previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6"
},
"logs" : [
],
"out" : "0x",
"post" : {
"a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"balance" : "100000",
"code" : "0x",
"nonce" : "10",
"storage" : {
}
}
},
"pre" : {
"a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"balance" : "100000",
"code" : "0x",
"nonce" : "10",
"storage" : {
}
}
},
"transaction" : {
"data" : "",
"gasLimit" : "1000",
"gasPrice" : "1",
"nonce" : "0",
"secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8",
"to" : "b94f5374fce5edbc8e2a8697c15331677e6ebf0b",
"value" : "10"
}
},
"TransactionNonceCheck2" : {
"env" : {
"currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
"currentDifficulty" : "45678256",
"currentGasLimit" : "1000000",
"currentNumber" : "0",
"currentTimestamp" : 1,
"previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6"
},
"logs" : [
],
"out" : "0x",
"post" : {
"a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"balance" : "100000",
"code" : "0x",
"nonce" : "0",
"storage" : {
}
}
},
"pre" : {
"a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"balance" : "100000",
"code" : "0x",
"nonce" : "0",
"storage" : {
}
}
},
"transaction" : {
"data" : "",
"gasLimit" : "1000",
"gasPrice" : "1",
"nonce" : "10",
"secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8",
"to" : "b94f5374fce5edbc8e2a8697c15331677e6ebf0b",
"value" : "10"
}
},
"TransactionSendingToEmpty" : { "TransactionSendingToEmpty" : {
"env" : { "env" : {
"currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", "currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
@ -755,5 +425,59 @@
"to" : "a94f5374fce5edbc8e2a8697c15331677e6ebf0b", "to" : "a94f5374fce5edbc8e2a8697c15331677e6ebf0b",
"value" : "502" "value" : "502"
} }
},
"TransactionTooManyRlpElements" : {
"env" : {
"currentCoinbase" : "b94f5374fce5edbc8e2a8697c15331677e6ebf0b",
"currentDifficulty" : "45678256",
"currentGasLimit" : "10000",
"currentNumber" : "0",
"currentTimestamp" : 1,
"previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6"
},
"logs" : [
],
"out" : "0x",
"post" : {
"a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"balance" : "93990",
"code" : "0x",
"nonce" : "1",
"storage" : {
}
},
"b94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"balance" : "6000",
"code" : "0x",
"nonce" : "0",
"storage" : {
}
},
"d2571607e241ecf590ed94b12d87c94babe36db6" : {
"balance" : "10",
"code" : "0x",
"nonce" : "0",
"storage" : {
}
}
},
"pre" : {
"a94f5374fce5edbc8e2a8697c15331677e6ebf0b" : {
"balance" : "100000",
"code" : "0x",
"nonce" : "0",
"storage" : {
}
}
},
"transaction" : {
"data" : "",
"gasLimit" : "1600",
"gasPrice" : "12",
"nonce" : "",
"secretKey" : "45a915e4d060149eb4365960e6a7a45f334393093061116b197e3240065ff2d8",
"to" : "d2571607e241ecf590ed94b12d87c94babe36db6",
"value" : "10"
}
} }
} }

File diff suppressed because one or more lines are too long

View file

@ -1,123 +0,0 @@
{
"EmptyTransaction" : {
"rlp" : "0xf8498080808080801ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804",
"sender" : "66c7b5c28121e4b66583d15481c92f5ad848fe1f",
"transaction" : {
"data" : "",
"gasLimit" : "",
"gasPrice" : "",
"nonce" : "",
"r" : "0x48b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353",
"s" : "0xefffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804",
"to" : "",
"v" : "27",
"value" : ""
}
},
"RLPElementsWithZeros" : {
"rlp" : "0xf8662c538203e894095e7baea6a6c7c4c2dfeb977efac326af552d870987000000112223331ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804",
"sender" : "f8cf3e78f097103c068225ce61e34f29078191a5",
"transaction" : {
"data" : "0x0000011222333",
"gasLimit" : "1000",
"gasPrice" : "00123",
"nonce" : "0054",
"r" : "0x48b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353",
"s" : "0xefffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804",
"to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87",
"v" : "27",
"value" : "00000011"
}
},
"RLPWrongHexElements" : {
"rlp" : "0xf864367b8203e894095e7baea6a6c7c4c2dfeb977efac326af552d870b8500000000121ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804",
"sender" : "65959aab09090881850fd56f8a1cacb3abc4e811",
"transaction" : {
"data" : "0x0000000012",
"gasLimit" : "1000",
"gasPrice" : "123",
"nonce" : "54",
"r" : "0x0048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353",
"s" : "0x00efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804",
"to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87",
"v" : "27",
"value" : "11"
}
},
"RightVRSTest" : {
"rlp" : "0xf86103018207d094b94f5374fce5edbc8e2a8697c15331677e6ebf0b0a8255441ca098ff921201554726367d2be8c804a7ff89ccf285ebc57dff8ae4c44b9c19ac4aa08887321be575c8095f789dd4c743dfe42c1820f9231f98a962b210e3ac2452a3",
"sender" : "5ba306ae3650c72c3586da6f1dbac3c9fa7e529e",
"transaction" : {
"data" : "0x5544",
"gasLimit" : "2000",
"gasPrice" : "1",
"nonce" : "3",
"r" : "0x98ff921201554726367d2be8c804a7ff89ccf285ebc57dff8ae4c44b9c19ac4a",
"s" : "0x8887321be575c8095f789dd4c743dfe42c1820f9231f98a962b210e3ac2452a3",
"to" : "b94f5374fce5edbc8e2a8697c15331677e6ebf0b",
"v" : "28",
"value" : "10"
}
},
"SenderTest" : {
"//" : "sender a94f5374fce5edbc8e2a8697c15331677e6ebf0b",
"rlp" : "0xf85f800182035294095e7baea6a6c7c4c2dfeb977efac326af552d870a801ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804",
"sender" : "a94f5374fce5edbc8e2a8697c15331677e6ebf0b",
"transaction" : {
"data" : "",
"gasLimit" : "850",
"gasPrice" : "1",
"nonce" : "0",
"r" : "0x48b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353",
"s" : "0xefffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804",
"to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87",
"v" : "27",
"value" : "10"
}
},
"TransactionWithGasLimitOverflow" : {
"rlp" : "0xf87e807ba101000000000000000000000000000000000000000000000000000000000000000094095e7baea6a6c7c4c2dfeb977efac326af552d870b801ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804"
},
"TransactionWithGasPriceOverflow" : {
"rlp" : "0xf88080a101000000000000000000000000000000000000000000000000000000000000000082035294095e7baea6a6c7c4c2dfeb977efac326af552d870b801ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804"
},
"TransactionWithHihghValue" : {
"rlp" : "0xf87f800182035294095e7baea6a6c7c4c2dfeb977efac326af552d87a0ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff801ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804",
"sender" : "50702f47f1c4bfc6b75e65e2b995a8024fe25be9",
"transaction" : {
"data" : "",
"gasLimit" : "850",
"gasPrice" : "1",
"nonce" : "0",
"r" : "0x48b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353",
"s" : "0xefffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804",
"to" : "095e7baea6a6c7c4c2dfeb977efac326af552d87",
"v" : "27",
"value" : "115792089237316195423570985008687907853269984665640564039457584007913129639935"
}
},
"TransactionWithHihghValueOverflow" : {
"rlp" : "0xf880800182035294095e7baea6a6c7c4c2dfeb977efac326af552d87a1010000000000000000000000000000000000000000000000000000000000000000801ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804"
},
"TransactionWithNonceOverflow" : {
"rlp" : "0xf880a10100000000000000000000000000000000000000000000000000000000000000000182035294095e7baea6a6c7c4c2dfeb977efac326af552d870b801ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804"
},
"TransactionWithRvalueOverflow" : {
"rlp" : "0xf85f800182035294095e7baea6a6c7c4c2dfeb977efac326af552d870b801ba0fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804"
},
"TransactionWithSvalueOverflow" : {
"rlp" : "0xf85f800182035294095e7baea6a6c7c4c2dfeb977efac326af552d870b801ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"
},
"TransactionWithTooFewRLPElements" : {
"rlp" : "0xf85b800194095e7baea6a6c7c4c2dfeb977efac326af552d87801ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804"
},
"TransactionWithTooManyRLPElements" : {
"rlp" : "0xf865800182035294095e7baea6a6c7c4c2dfeb977efac326af552d870a801ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804851de98d0edd"
},
"WrongVRSTestVge31" : {
"rlp" : "0xf85f80018207d094b94f5374fce5edbc8e2a8697c15331677e6ebf0b0a801fa098ff921201554726367d2be8c804a7ff89ccf285ebc57dff8ae4c44b9c19ac4aa08887321be575c8095f789dd4c743dfe42c1820f9231f98a962b210e3ac2452a3"
},
"WrongVRSTestVl27" : {
"rlp" : "0xf85f80018207d094b94f5374fce5edbc8e2a8697c15331677e6ebf0b0a801aa098ff921201554726367d2be8c804a7ff89ccf285ebc57dff8ae4c44b9c19ac4aa08887321be575c8095f789dd4c743dfe42c1820f9231f98a962b210e3ac2452a3"
}
}

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