mirror of
https://github.com/ethereum/go-ethereum.git
synced 2026-07-19 19:30:44 +00:00
Merging from develop
This commit is contained in:
commit
9047f5dd4c
127 changed files with 9457 additions and 1705 deletions
|
|
@ -21,6 +21,7 @@ before_script:
|
|||
# - go test -race ./...
|
||||
script:
|
||||
- ./gocoverage.sh
|
||||
- if [ "$COVERALLS_TOKEN" ]; then goveralls -coverprofile=profile.cov -service=travis-ci -repotoken $COVERALLS_TOKEN; fi
|
||||
env:
|
||||
global:
|
||||
- PKG_CONFIG_PATH=/opt/qt54/lib/pkgconfig
|
||||
|
|
|
|||
19
README.md
19
README.md
|
|
@ -1,19 +1,18 @@
|
|||
## Ethereum Go
|
||||
|
||||
Ethereum Go Client © 2014 Jeffrey Wilcke.
|
||||
|
||||
| Linux | OSX | Windows
|
||||
----------|---------|-----|--------
|
||||
develop | [](http://build.ethdev.com/builders/Linux%20Go%20develop%20branch/builds/-1) | [](http://build.ethdev.com/builders/OSX%20Go%20develop%20branch/builds/-1) | N/A
|
||||
master | [](http://build.ethdev.com/builders/Linux%20Go%20master%20branch/builds/-1) | [](http://build.ethdev.com/builders/OSX%20Go%20master%20branch/builds/-1) | N/A
|
||||
|
||||
[](https://waffle.io/ethereum/go-ethereum)
|
||||
[](https://waffle.io/ethereum/go-ethereum)
|
||||
[](http://waffle.io/ethereum/go-ethereum)
|
||||
[](https://gitter.im/ethereum/go-ethereum?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
|
||||
|
||||
|
||||
Ethereum PoC-8
|
||||
========
|
||||
|
||||
* [](http://build.ethdev.com:8010/builders/Linux%20Go%20master%20branch/builds/-1) master
|
||||
* [](http://build.ethdev.com:8010/builders/Linux%20Go%20develop%20branch/builds/-1) develop
|
||||
* [](https://travis-ci.org/ethereum/go-ethereum) travis-ci
|
||||
* [](https://coveralls.io/r/ethereum/go-ethereum?branch=develop)
|
||||
|
||||
Ethereum Go Client © 2014 Jeffrey Wilcke.
|
||||
|
||||
Build
|
||||
=====
|
||||
|
||||
|
|
|
|||
|
|
@ -49,7 +49,7 @@ var (
|
|||
AddPeer string
|
||||
MaxPeer int
|
||||
GenAddr bool
|
||||
UseSeed bool
|
||||
SeedNode string
|
||||
SecretFile string
|
||||
ExportDir string
|
||||
NonInteractive bool
|
||||
|
|
@ -96,12 +96,12 @@ func Init() {
|
|||
flag.StringVar(&NatType, "nat", "", "NAT support (UPNP|PMP) (none)")
|
||||
flag.StringVar(&PMPGateway, "pmp", "", "Gateway IP for PMP")
|
||||
flag.IntVar(&MaxPeer, "maxpeer", 30, "maximum desired peers")
|
||||
flag.IntVar(&RpcPort, "rpcport", 8080, "port to start json-rpc server on")
|
||||
flag.IntVar(&RpcPort, "rpcport", 8545, "port to start json-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(&StartWebSockets, "ws", false, "start websocket server")
|
||||
flag.BoolVar(&NonInteractive, "y", false, "non-interactive mode (say yes to confirmations)")
|
||||
flag.BoolVar(&UseSeed, "seed", true, "seed peers")
|
||||
flag.StringVar(&SeedNode, "seednode", "poc-8.ethdev.com:30303", "ip:port of seed node to connect to. Set to blank for skip")
|
||||
flag.BoolVar(&SHH, "shh", true, "whisper protocol (on)")
|
||||
flag.BoolVar(&Dial, "dial", true, "dial out connections (on)")
|
||||
flag.BoolVar(&GenAddr, "genaddr", false, "create a new priv/pub key")
|
||||
|
|
|
|||
|
|
@ -134,7 +134,7 @@ func main() {
|
|||
utils.StartWebSockets(ethereum, WsPort)
|
||||
}
|
||||
|
||||
utils.StartEthereum(ethereum, UseSeed)
|
||||
utils.StartEthereum(ethereum, SeedNode)
|
||||
|
||||
if StartJsConsole {
|
||||
InitJsConsole(ethereum)
|
||||
|
|
|
|||
|
|
@ -128,6 +128,7 @@ func (self *VMEnv) Difficulty() *big.Int { return ethutil.Big1 }
|
|||
func (self *VMEnv) BlockHash() []byte { return make([]byte, 32) }
|
||||
func (self *VMEnv) Value() *big.Int { return self.value }
|
||||
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) SetDepth(i int) { self.depth = i }
|
||||
func (self *VMEnv) GetHash(n uint64) []byte {
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@
|
|||
}];
|
||||
var address = web3.eth.transact({
|
||||
data: "0x603880600c6000396000f3006001600060e060020a600035048063c6888fa114601857005b6021600435602b565b8060005260206000f35b600081600702905091905056",
|
||||
gasprice: "1000000000000000",
|
||||
gasPrice: "1000000000000000",
|
||||
gas: "10000",
|
||||
});
|
||||
var contract = web3.eth.contract(address, desc);
|
||||
|
|
|
|||
|
|
@ -32,17 +32,19 @@
|
|||
web3.setProvider(new web3.providers.HttpSyncProvider('http://localhost:8080'));
|
||||
var desc = [{
|
||||
"name": "balance(address)",
|
||||
"type": "function",
|
||||
"inputs": [{
|
||||
"name": "who",
|
||||
"type": "address"
|
||||
}],
|
||||
"const": true,
|
||||
"constant": true,
|
||||
"outputs": [{
|
||||
"name": "value",
|
||||
"type": "uint256"
|
||||
}]
|
||||
}, {
|
||||
"name": "send(address,uint256)",
|
||||
"type": "function",
|
||||
"inputs": [{
|
||||
"name": "to",
|
||||
"type": "address"
|
||||
|
|
@ -51,23 +53,33 @@
|
|||
"type": "uint256"
|
||||
}],
|
||||
"outputs": []
|
||||
}, {
|
||||
"name":"Changed",
|
||||
"type":"event",
|
||||
"inputs": [
|
||||
{"name":"to","type":"address","indexed":true},
|
||||
{"name":"amount","type":"uint256","indexed":false},
|
||||
],
|
||||
}];
|
||||
|
||||
var address = web3.db.get("jevcoin", "address");
|
||||
if( address.length == 0 ) {
|
||||
var code = "0x60056011565b60ae8060356000396000f35b64174876e800600033600160a060020a031660005260205260406000208190555056006001600060e060020a600035048063d0679d34146022578063e3d670d714603457005b602e6004356024356047565b60006000f35b603d600435608d565b8060005260206000f35b80600083600160a060020a0316600052602052604060002090815401908190555080600033600160a060020a031660005260205260406000209081540390819055505050565b6000600082600160a060020a0316600052602052604060002054905091905056";
|
||||
var code = "0x60056011565b60b88060356000396000f35b64e8d4a51000600033600160a060020a0316600052602052604060002081905550560060e060020a6000350480637bb98a68146028578063d0679d34146034578063e3d670d714604657005b602e60b3565b60006000f35b60406004356024356059565b60006000f35b604f6004356091565b8060005260206000f35b8060005281600160a060020a03167fb52dda022b6c1a1f40905a85f257f689aa5d69d850e49cf939d688fbe5af594660206000a25050565b6000600082600160a060020a03166000526020526040600020549050919050565b5b60008156";
|
||||
address = web3.eth.transact({
|
||||
data: code,
|
||||
gasprice: "1000000000000000",
|
||||
gasPrice: "1000000000000000",
|
||||
gas: "10000",
|
||||
});
|
||||
web3.db.put("jevcoin", "address", address);
|
||||
}
|
||||
|
||||
var contract = web3.eth.contract(address, desc);
|
||||
|
||||
contract.Changed({to: "0xaa"}).changed(function(e) {
|
||||
console.log("e: " + JSON.stringify(e));
|
||||
});
|
||||
contract.send( "0xaa", 10000 );
|
||||
function reflesh() {
|
||||
document.querySelector("#balance").innerHTML = contract.call().balance(eth.coinbase);
|
||||
document.querySelector("#balance").innerHTML = contract.balance(eth.coinbase);
|
||||
|
||||
var table = document.querySelector("#table");
|
||||
table.innerHTML = ""; // clear
|
||||
|
|
|
|||
|
|
@ -30,6 +30,10 @@
|
|||
<td id="accounts"></td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>Balance</td>
|
||||
<td id="balance"></td>
|
||||
|
||||
<tr>
|
||||
<td>Gas price</td>
|
||||
<td id="gas_price"></td>
|
||||
|
|
@ -63,6 +67,7 @@
|
|||
document.querySelector("#peer_count").innerHTML = eth.peerCount;
|
||||
document.querySelector("#default_block").innerHTML = eth.defaultBlock;
|
||||
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("#mining").innerHTML = eth.mining;
|
||||
document.querySelector("#listening").innerHTML = eth.listening;
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@
|
|||
<h1>Whisper test</h1>
|
||||
|
||||
<button onclick="test()">Send</button>
|
||||
<button onclick="test2()">Private send</button>
|
||||
|
||||
<table width="100%" id="table">
|
||||
<tr>
|
||||
|
|
@ -44,10 +45,19 @@
|
|||
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() {
|
||||
shh.post({topics: ["test"], payload: web3.fromAscii("test it")});
|
||||
count();
|
||||
}
|
||||
|
||||
function test2() {
|
||||
shh.post({to: id, topics: ["test"], payload: web3.fromAscii("Private")});
|
||||
count();
|
||||
}
|
||||
|
||||
function count() {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
{
|
||||
"name": "ethereum.js",
|
||||
"namespace": "ethereum",
|
||||
"version": "0.0.10",
|
||||
"version": "0.0.13",
|
||||
"description": "Ethereum Compatible JavaScript API",
|
||||
"main": ["./dist/ethereum.js", "./dist/ethereum.min.js"],
|
||||
"dependencies": {
|
||||
|
|
|
|||
1717
cmd/mist/assets/ext/ethereum.js/dist/ethereum.js
vendored
1717
cmd/mist/assets/ext/ethereum.js/dist/ethereum.js
vendored
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
|
|
@ -17,7 +17,11 @@
|
|||
var originalBalance = web3.toDecimal(balance);
|
||||
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() {
|
||||
=======
|
||||
web3.eth.watch('pending').changed(function() {
|
||||
>>>>>>> 859a1999cb204d2c6fcb08d6569c738c5af5cd86:example/balance.html
|
||||
balance = web3.eth.balanceAt(coinbase)
|
||||
var currentBalance = web3.toDecimal(balance);
|
||||
document.getElementById("current").innerText = 'current: ' + currentBalance;
|
||||
|
|
|
|||
|
|
@ -20,6 +20,7 @@
|
|||
// contract description, this will be autogenerated somehow
|
||||
var desc = [{
|
||||
"name": "multiply(uint256)",
|
||||
"type": "function",
|
||||
"inputs": [
|
||||
{
|
||||
"name": "a",
|
||||
|
|
|
|||
|
|
@ -0,0 +1,76 @@
|
|||
<!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>
|
||||
|
||||
120
cmd/mist/assets/ext/ethereum.js/example/event.html
Normal file
120
cmd/mist/assets/ext/ethereum.js/example/event.html
Normal file
|
|
@ -0,0 +1,120 @@
|
|||
<!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>
|
||||
66
cmd/mist/assets/ext/ethereum.js/example/event_inc.html
Normal file
66
cmd/mist/assets/ext/ethereum.js/example/event_inc.html
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
<!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>
|
||||
|
|
@ -21,6 +21,7 @@
|
|||
// contract description, this will be autogenerated somehow
|
||||
var desc = [{
|
||||
"name": "multiply(uint256)",
|
||||
"type": "function",
|
||||
"inputs": [
|
||||
{
|
||||
"name": "a",
|
||||
|
|
|
|||
|
|
@ -21,175 +21,57 @@
|
|||
* @date 2014
|
||||
*/
|
||||
|
||||
// TODO: is these line is supposed to be here?
|
||||
if (process.env.NODE_ENV !== 'build') {
|
||||
var BigNumber = require('bignumber.js'); // jshint ignore:line
|
||||
}
|
||||
var web3 = require('./web3');
|
||||
var utils = require('./utils');
|
||||
var types = require('./types');
|
||||
var c = require('./const');
|
||||
var f = require('./formatters');
|
||||
|
||||
var web3 = require('./web3'); // jshint ignore:line
|
||||
|
||||
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;
|
||||
};
|
||||
var displayTypeError = function (type) {
|
||||
console.error('parser does not support type: ' + 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) {
|
||||
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) {
|
||||
// TODO: decide what to do with array of strings
|
||||
if (arrayType(type) || type === 'string') // only string itself that is dynamic; stringX is static length.
|
||||
return formatInputInt(value.length);
|
||||
return f.formatInputInt(value.length);
|
||||
return "";
|
||||
};
|
||||
|
||||
/// 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();
|
||||
var inputTypes = types.inputTypes();
|
||||
|
||||
/// Formats input params to bytes
|
||||
/// @param contract json abi
|
||||
/// @param name of the method that we want to use
|
||||
/// @param abi contract method inputs
|
||||
/// @param array of params that will be formatted to bytes
|
||||
/// @returns bytes representation of input params
|
||||
var toAbiInput = function (json, methodName, params) {
|
||||
var formatInput = function (inputs, params) {
|
||||
var bytes = "";
|
||||
|
||||
var method = getMethodWithName(json, methodName);
|
||||
var padding = ETH_PADDING * 2;
|
||||
var padding = c.ETH_PADDING * 2;
|
||||
|
||||
/// first we iterate in search for dynamic
|
||||
method.inputs.forEach(function (input, index) {
|
||||
inputs.forEach(function (input, index) {
|
||||
bytes += dynamicTypeBytes(input.type, params[index]);
|
||||
});
|
||||
|
||||
method.inputs.forEach(function (input, i) {
|
||||
inputs.forEach(function (input, i) {
|
||||
var typeMatch = false;
|
||||
for (var j = 0; j < inputTypes.length && !typeMatch; j++) {
|
||||
typeMatch = inputTypes[j].type(method.inputs[i].type, params[i]);
|
||||
typeMatch = inputTypes[j].type(inputs[i].type, params[i]);
|
||||
}
|
||||
if (!typeMatch) {
|
||||
console.error('input parser does not support type: ' + method.inputs[i].type);
|
||||
displayTypeError(inputs[i].type);
|
||||
}
|
||||
|
||||
var formatter = inputTypes[j - 1].format;
|
||||
var toAppend = "";
|
||||
|
||||
if (arrayType(method.inputs[i].type))
|
||||
if (arrayType(inputs[i].type))
|
||||
toAppend = params[i].reduce(function (acc, curr) {
|
||||
return acc + formatter(curr);
|
||||
}, "");
|
||||
|
|
@ -201,118 +83,44 @@ var toAbiInput = function (json, methodName, params) {
|
|||
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) {
|
||||
if (arrayType(type) || type === 'string') // only string itself that is dynamic; stringX is static length.
|
||||
return ETH_PADDING * 2;
|
||||
return c.ETH_PADDING * 2;
|
||||
return 0;
|
||||
};
|
||||
|
||||
/// 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();
|
||||
var outputTypes = types.outputTypes();
|
||||
|
||||
/// Formats output bytes back to param list
|
||||
/// @param contract json abi
|
||||
/// @param name of the method that we want to use
|
||||
/// @param contract abi method outputs
|
||||
/// @param bytes representtion of output
|
||||
/// @returns array of output params
|
||||
var fromAbiOutput = function (json, methodName, output) {
|
||||
var formatOutput = function (outs, output) {
|
||||
|
||||
output = output.slice(2);
|
||||
var result = [];
|
||||
var method = getMethodWithName(json, methodName);
|
||||
var padding = ETH_PADDING * 2;
|
||||
var padding = c.ETH_PADDING * 2;
|
||||
|
||||
var dynamicPartLength = method.outputs.reduce(function (acc, curr) {
|
||||
var dynamicPartLength = outs.reduce(function (acc, curr) {
|
||||
return acc + dynamicBytesLength(curr.type);
|
||||
}, 0);
|
||||
|
||||
var dynamicPart = output.slice(0, dynamicPartLength);
|
||||
output = output.slice(dynamicPartLength);
|
||||
|
||||
method.outputs.forEach(function (out, i) {
|
||||
outs.forEach(function (out, i) {
|
||||
var typeMatch = false;
|
||||
for (var j = 0; j < outputTypes.length && !typeMatch; j++) {
|
||||
typeMatch = outputTypes[j].type(method.outputs[i].type);
|
||||
typeMatch = outputTypes[j].type(outs[i].type);
|
||||
}
|
||||
|
||||
if (!typeMatch) {
|
||||
console.error('output parser does not support type: ' + method.outputs[i].type);
|
||||
displayTypeError(outs[i].type);
|
||||
}
|
||||
|
||||
var formatter = outputTypes[j - 1].format;
|
||||
if (arrayType(method.outputs[i].type)) {
|
||||
var size = formatOutputUInt(dynamicPart.slice(0, padding));
|
||||
if (arrayType(outs[i].type)) {
|
||||
var size = f.formatOutputUInt(dynamicPart.slice(0, padding));
|
||||
dynamicPart = dynamicPart.slice(padding);
|
||||
var array = [];
|
||||
for (var k = 0; k < size; k++) {
|
||||
|
|
@ -321,7 +129,7 @@ var fromAbiOutput = function (json, methodName, output) {
|
|||
}
|
||||
result.push(array);
|
||||
}
|
||||
else if (prefixedType('string')(method.outputs[i].type)) {
|
||||
else if (types.prefixedType('string')(outs[i].type)) {
|
||||
dynamicPart = dynamicPart.slice(padding);
|
||||
result.push(formatter(output.slice(0, padding)));
|
||||
output = output.slice(padding);
|
||||
|
|
@ -334,30 +142,18 @@ var fromAbiOutput = function (json, methodName, output) {
|
|||
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
|
||||
/// @returns input parser object for given json abi
|
||||
/// TODO: refactor creating the parser, do not double logic from contract
|
||||
var inputParser = function (json) {
|
||||
var parser = {};
|
||||
json.forEach(function (method) {
|
||||
var displayName = methodDisplayName(method.name);
|
||||
var typeName = methodTypeName(method.name);
|
||||
var displayName = utils.extractDisplayName(method.name);
|
||||
var typeName = utils.extractTypeName(method.name);
|
||||
|
||||
var impl = function () {
|
||||
var params = Array.prototype.slice.call(arguments);
|
||||
return toAbiInput(json, method.name, params);
|
||||
return formatInput(method.inputs, params);
|
||||
};
|
||||
|
||||
if (parser[displayName] === undefined) {
|
||||
|
|
@ -376,11 +172,11 @@ var outputParser = function (json) {
|
|||
var parser = {};
|
||||
json.forEach(function (method) {
|
||||
|
||||
var displayName = methodDisplayName(method.name);
|
||||
var typeName = methodTypeName(method.name);
|
||||
var displayName = utils.extractDisplayName(method.name);
|
||||
var typeName = utils.extractTypeName(method.name);
|
||||
|
||||
var impl = function (output) {
|
||||
return fromAbiOutput(json, method.name, output);
|
||||
return formatOutput(method.outputs, output);
|
||||
};
|
||||
|
||||
if (parser[displayName] === undefined) {
|
||||
|
|
@ -393,18 +189,22 @@ var outputParser = function (json) {
|
|||
return parser;
|
||||
};
|
||||
|
||||
/// @param method name for which we want to get method signature
|
||||
/// @returns (promise) contract method signature for method with given name
|
||||
var methodSignature = function (name) {
|
||||
return web3.sha3(web3.fromAscii(name)).slice(0, 2 + ETH_METHOD_SIGNATURE_LENGTH * 2);
|
||||
/// @param function/event name for which we want to get signature
|
||||
/// @returns signature of function/event with given name
|
||||
var signatureFromAscii = function (name) {
|
||||
return web3.sha3(web3.fromAscii(name)).slice(0, 2 + c.ETH_SIGNATURE_LENGTH * 2);
|
||||
};
|
||||
|
||||
var eventSignatureFromAscii = function (name) {
|
||||
return web3.sha3(web3.fromAscii(name));
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
inputParser: inputParser,
|
||||
outputParser: outputParser,
|
||||
methodSignature: methodSignature,
|
||||
methodDisplayName: methodDisplayName,
|
||||
methodTypeName: methodTypeName,
|
||||
getMethodWithName: getMethodWithName
|
||||
formatInput: formatInput,
|
||||
formatOutput: formatOutput,
|
||||
signatureFromAscii: signatureFromAscii,
|
||||
eventSignatureFromAscii: eventSignatureFromAscii
|
||||
};
|
||||
|
||||
|
|
|
|||
56
cmd/mist/assets/ext/ethereum.js/lib/const.js
Normal file
56
cmd/mist/assets/ext/ethereum.js/lib/const.js
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
/*
|
||||
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 }
|
||||
};
|
||||
|
||||
|
|
@ -20,8 +20,153 @@
|
|||
* @date 2014
|
||||
*/
|
||||
|
||||
var web3 = require('./web3'); // jshint ignore:line
|
||||
var web3 = require('./web3');
|
||||
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
|
||||
|
|
@ -47,10 +192,11 @@ var abi = require('./abi');
|
|||
|
||||
var contract = function (address, desc) {
|
||||
|
||||
// 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
|
||||
// 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) {
|
||||
// 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
|
||||
// prototype, so we make it so as a workaround.
|
||||
if (method.name.indexOf('(') === -1) {
|
||||
var displayName = method.name;
|
||||
var typeName = method.inputs.map(function(i){return i.type; }).join();
|
||||
|
|
@ -58,85 +204,11 @@ var contract = function (address, desc) {
|
|||
}
|
||||
});
|
||||
|
||||
var inputParser = abi.inputParser(desc);
|
||||
var outputParser = abi.outputParser(desc);
|
||||
|
||||
var result = {};
|
||||
|
||||
result.call = function (options) {
|
||||
result._isTransact = false;
|
||||
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;
|
||||
|
||||
});
|
||||
addFunctionRelatedPropertiesToContract(result);
|
||||
addFunctionsToContract(result, desc, address);
|
||||
addEventRelatedPropertiesToContract(result, desc, address);
|
||||
addEventsToContract(result, desc, address);
|
||||
|
||||
return result;
|
||||
};
|
||||
|
|
|
|||
135
cmd/mist/assets/ext/ethereum.js/lib/event.js
Normal file
135
cmd/mist/assets/ext/ethereum.js/lib/event.js
Normal file
|
|
@ -0,0 +1,135 @@
|
|||
/*
|
||||
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
|
||||
};
|
||||
|
||||
|
|
@ -27,18 +27,45 @@ var web3 = require('./web3'); // jshint ignore:line
|
|||
|
||||
/// should be used when we want to watch something
|
||||
/// 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) {
|
||||
|
||||
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.callbacks = [];
|
||||
|
||||
this.id = impl.newFilter(options);
|
||||
web3.provider.startPolling({call: impl.changed, args: [this.id]}, this.id, this.trigger.bind(this));
|
||||
web3.provider.startPolling({method: impl.changed, params: [this.id]}, this.id, this.trigger.bind(this));
|
||||
};
|
||||
|
||||
/// alias for changed*
|
||||
Filter.prototype.arrived = function(callback) {
|
||||
this.changed(callback);
|
||||
};
|
||||
Filter.prototype.happened = function(callback) {
|
||||
this.changed(callback);
|
||||
};
|
||||
|
||||
/// gets called when there is new eth/shh message
|
||||
Filter.prototype.changed = function(callback) {
|
||||
|
|
@ -49,7 +76,8 @@ Filter.prototype.changed = function(callback) {
|
|||
Filter.prototype.trigger = function(messages) {
|
||||
for (var i = 0; i < this.callbacks.length; i++) {
|
||||
for (var j = 0; j < messages.length; j++) {
|
||||
this.callbacks[i].call(this, messages[j]);
|
||||
var message = this._onWatchResult ? this._onWatchResult(messages[j]) : messages[j];
|
||||
this.callbacks[i].call(this, message);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
|
|
|||
154
cmd/mist/assets/ext/ethereum.js/lib/formatters.js
Normal file
154
cmd/mist/assets/ext/ethereum.js/lib/formatters.js
Normal file
|
|
@ -0,0 +1,154 @@
|
|||
/*
|
||||
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
|
||||
};
|
||||
|
||||
|
|
@ -30,40 +30,16 @@ var HttpSyncProvider = function (host) {
|
|||
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) {
|
||||
var data = formatJsonRpcObject(payload);
|
||||
//var data = formatJsonRpcObject(payload);
|
||||
|
||||
var request = new XMLHttpRequest();
|
||||
request.open('POST', this.host, false);
|
||||
request.send(JSON.stringify(data));
|
||||
request.send(JSON.stringify(payload));
|
||||
|
||||
// check request.status
|
||||
return request.responseText;
|
||||
var result = request.responseText;
|
||||
return JSON.parse(result);
|
||||
};
|
||||
|
||||
module.exports = HttpSyncProvider;
|
||||
|
|
|
|||
65
cmd/mist/assets/ext/ethereum.js/lib/jsonrpc.js
Normal file
65
cmd/mist/assets/ext/ethereum.js/lib/jsonrpc.js
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
/*
|
||||
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
|
||||
};
|
||||
|
||||
|
||||
|
|
@ -23,7 +23,9 @@
|
|||
* @date 2014
|
||||
*/
|
||||
|
||||
var web3 = require('./web3'); // jshint ignore:line
|
||||
var web3 = require('./web3');
|
||||
var jsonrpc = require('./jsonrpc');
|
||||
|
||||
|
||||
/**
|
||||
* Provider manager object prototype
|
||||
|
|
@ -37,48 +39,38 @@ var web3 = require('./web3'); // jshint ignore:line
|
|||
var ProviderManager = function() {
|
||||
this.polls = [];
|
||||
this.provider = undefined;
|
||||
this.id = 1;
|
||||
|
||||
var self = this;
|
||||
var poll = function () {
|
||||
if (self.provider) {
|
||||
self.polls.forEach(function (data) {
|
||||
data.data._id = self.id;
|
||||
self.id++;
|
||||
var result = self.provider.send(data.data);
|
||||
|
||||
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;
|
||||
}
|
||||
self.polls.forEach(function (data) {
|
||||
var result = self.send(data.data);
|
||||
|
||||
if (!(result instanceof Array) || result.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
data.callback(result);
|
||||
});
|
||||
|
||||
data.callback(result.result);
|
||||
});
|
||||
}
|
||||
setTimeout(poll, 1000);
|
||||
};
|
||||
poll();
|
||||
};
|
||||
|
||||
/// sends outgoing requests
|
||||
/// @params data - an object with at least 'method' property
|
||||
ProviderManager.prototype.send = function(data) {
|
||||
|
||||
data.args = data.args || [];
|
||||
data._id = this.id++;
|
||||
var payload = jsonrpc.toPayload(data.method, data.params);
|
||||
|
||||
if (this.provider === undefined) {
|
||||
console.error('provider is not set');
|
||||
return null;
|
||||
}
|
||||
|
||||
//TODO: handle error here?
|
||||
var result = this.provider.send(data);
|
||||
result = JSON.parse(result);
|
||||
var result = this.provider.send(payload);
|
||||
|
||||
if (result.error) {
|
||||
console.log(result.error);
|
||||
if (!jsonrpc.isValidResponse(result)) {
|
||||
console.log(result);
|
||||
return null;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -25,7 +25,8 @@ var QtSyncProvider = function () {
|
|||
};
|
||||
|
||||
QtSyncProvider.prototype.send = function (payload) {
|
||||
return navigator.qt.callMethod(JSON.stringify(payload));
|
||||
var result = navigator.qt.callMethod(JSON.stringify(payload));
|
||||
return JSON.parse(result);
|
||||
};
|
||||
|
||||
module.exports = QtSyncProvider;
|
||||
|
|
|
|||
79
cmd/mist/assets/ext/ethereum.js/lib/types.js
Normal file
79
cmd/mist/assets/ext/ethereum.js/lib/types.js
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
/*
|
||||
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
|
||||
};
|
||||
|
||||
142
cmd/mist/assets/ext/ethereum.js/lib/utils.js
Normal file
142
cmd/mist/assets/ext/ethereum.js/lib/utils.js
Normal file
|
|
@ -0,0 +1,142 @@
|
|||
/*
|
||||
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
|
||||
};
|
||||
|
||||
|
|
@ -27,27 +27,7 @@ if (process.env.NODE_ENV !== 'build') {
|
|||
var BigNumber = require('bignumber.js');
|
||||
}
|
||||
|
||||
var ETH_UNITS = [
|
||||
'wei',
|
||||
'Kwei',
|
||||
'Mwei',
|
||||
'Gwei',
|
||||
'szabo',
|
||||
'finney',
|
||||
'ether',
|
||||
'grand',
|
||||
'Mether',
|
||||
'Gether',
|
||||
'Tether',
|
||||
'Pether',
|
||||
'Eether',
|
||||
'Zether',
|
||||
'Yether',
|
||||
'Nether',
|
||||
'Dether',
|
||||
'Vether',
|
||||
'Uether'
|
||||
];
|
||||
var utils = require('./utils');
|
||||
|
||||
/// @returns an array of objects describing web3 api methods
|
||||
var web3Methods = function () {
|
||||
|
|
@ -156,8 +136,8 @@ var setupMethods = function (obj, methods) {
|
|||
var args = Array.prototype.slice.call(arguments);
|
||||
var call = typeof method.call === 'function' ? method.call(args) : method.call;
|
||||
return web3.provider.send({
|
||||
call: call,
|
||||
args: args
|
||||
method: call,
|
||||
params: args
|
||||
});
|
||||
};
|
||||
});
|
||||
|
|
@ -170,15 +150,15 @@ var setupProperties = function (obj, properties) {
|
|||
var proto = {};
|
||||
proto.get = function () {
|
||||
return web3.provider.send({
|
||||
call: property.getter
|
||||
method: property.getter
|
||||
});
|
||||
};
|
||||
|
||||
if (property.setter) {
|
||||
proto.set = function (val) {
|
||||
return web3.provider.send({
|
||||
call: property.setter,
|
||||
args: [val]
|
||||
method: property.setter,
|
||||
params: [val]
|
||||
});
|
||||
};
|
||||
}
|
||||
|
|
@ -192,43 +172,11 @@ var web3 = {
|
|||
_events: {},
|
||||
providers: {},
|
||||
|
||||
toHex: function(str) {
|
||||
var hex = "";
|
||||
for(var i = 0; i < str.length; i++) {
|
||||
var n = str.charCodeAt(i).toString(16);
|
||||
hex += n.length < 2 ? '0' + n : n;
|
||||
}
|
||||
|
||||
return hex;
|
||||
},
|
||||
|
||||
/// @returns ascii string representation of hex value prefixed with 0x
|
||||
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;
|
||||
},
|
||||
toAscii: utils.toAscii,
|
||||
|
||||
/// @returns hex representation (prefixed by 0x) of ascii string
|
||||
fromAscii: function(str, pad) {
|
||||
pad = pad === undefined ? 0 : pad;
|
||||
var hex = this.toHex(str);
|
||||
while(hex.length < pad*2)
|
||||
hex += "00";
|
||||
return "0x" + hex;
|
||||
},
|
||||
fromAscii: utils.fromAscii,
|
||||
|
||||
/// @returns decimal representaton of hex value prefixed by 0x
|
||||
toDecimal: function (val) {
|
||||
|
|
@ -243,29 +191,7 @@ var web3 = {
|
|||
},
|
||||
|
||||
/// used to transform value/string to eth string
|
||||
/// 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];
|
||||
},
|
||||
toEth: utils.toEth,
|
||||
|
||||
/// eth object prototype
|
||||
eth: {
|
||||
|
|
@ -278,8 +204,15 @@ var web3 = {
|
|||
return ret;
|
||||
};
|
||||
},
|
||||
watch: function (params) {
|
||||
return new web3.filter(params, ethWatch);
|
||||
|
||||
/// @param filter may be a string, object or event
|
||||
/// @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);
|
||||
}
|
||||
},
|
||||
|
||||
|
|
@ -288,15 +221,12 @@ var web3 = {
|
|||
|
||||
/// shh object prototype
|
||||
shh: {
|
||||
watch: function (params) {
|
||||
return new web3.filter(params, shhWatch);
|
||||
|
||||
/// @param filter may be a string, object or event
|
||||
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
|
||||
|
|
@ -319,7 +249,6 @@ var shhWatch = {
|
|||
setupMethods(shhWatch, shhWatchMethods());
|
||||
|
||||
web3.setProvider = function(provider) {
|
||||
//provider.onmessage = messageHandler; // there will be no async calls, to remove
|
||||
web3.provider.set(provider);
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
{
|
||||
"name": "ethereum.js",
|
||||
"namespace": "ethereum",
|
||||
"version": "0.0.10",
|
||||
"version": "0.0.13",
|
||||
"description": "Ethereum Compatible JavaScript API",
|
||||
"main": "./index.js",
|
||||
"directories": {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
|
||||
var assert = require('assert');
|
||||
var web3 = require('../index.js');
|
||||
var u = require('./utils.js');
|
||||
var u = require('./test.utils.js');
|
||||
|
||||
describe('web3', function() {
|
||||
describe('db', function() {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
var assert = require('assert');
|
||||
var web3 = require('../index.js');
|
||||
var u = require('./utils.js');
|
||||
var u = require('./test.utils.js');
|
||||
|
||||
describe('web3', function() {
|
||||
describe('eth', function() {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
var assert = require('assert');
|
||||
var web3 = require('../index.js');
|
||||
var u = require('./utils.js');
|
||||
var u = require('./test.utils.js');
|
||||
|
||||
describe('web3', function() {
|
||||
describe('shh', function() {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
var assert = require('assert');
|
||||
var web3 = require('../index.js');
|
||||
var u = require('./utils.js');
|
||||
var u = require('./test.utils.js');
|
||||
|
||||
describe('web3', function() {
|
||||
u.methodExists(web3, 'sha3');
|
||||
|
|
|
|||
83
cmd/mist/assets/html/home.html
Normal file
83
cmd/mist/assets/html/home.html
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
<!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>
|
||||
|
||||
BIN
cmd/mist/assets/html/logo.png
Normal file
BIN
cmd/mist/assets/html/logo.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 12 KiB |
|
|
@ -111,7 +111,7 @@ Rectangle {
|
|||
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)})
|
||||
} else {
|
||||
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)})
|
||||
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)})
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -29,6 +29,7 @@ import (
|
|||
|
||||
"github.com/ethereum/go-ethereum/cmd/utils"
|
||||
"github.com/ethereum/go-ethereum/core"
|
||||
"github.com/ethereum/go-ethereum/core/types"
|
||||
"github.com/ethereum/go-ethereum/ethutil"
|
||||
"github.com/ethereum/go-ethereum/state"
|
||||
"github.com/ethereum/go-ethereum/vm"
|
||||
|
|
@ -154,14 +155,17 @@ func (self *DebuggerWindow) Debug(valueStr, gasStr, gasPriceStr, scriptStr, data
|
|||
|
||||
block := self.lib.eth.ChainManager().CurrentBlock()
|
||||
|
||||
env := utils.NewEnv(self.lib.eth.ChainManager(), statedb, block, account.Address(), value)
|
||||
msg := types.NewTransactionMessage(nil, value, gas, gasPrice, data)
|
||||
env := core.NewEnv(statedb, self.lib.eth.ChainManager(), msg, block)
|
||||
|
||||
self.Logf("callsize %d", len(script))
|
||||
go func() {
|
||||
pgas := new(big.Int).Set(gas)
|
||||
ret, err := env.Call(account, contract.Address(), data, gas, gasPrice, ethutil.Big0)
|
||||
//ret, g, err := callerClosure.Call(evm, data)
|
||||
tot := new(big.Int).Mul(env.Gas, gasPrice)
|
||||
self.Logf("gas usage %v total price = %v (%v)", env.Gas, tot, ethutil.CurrencyToString(tot))
|
||||
|
||||
rgas := new(big.Int).Sub(pgas, gas)
|
||||
tot := new(big.Int).Mul(rgas, gasPrice)
|
||||
self.Logf("gas usage %v total price = %v (%v)", rgas, tot, ethutil.CurrencyToString(tot))
|
||||
if err != nil {
|
||||
self.Logln("exited with errors:", err)
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -51,7 +51,7 @@ var (
|
|||
AddPeer string
|
||||
MaxPeer int
|
||||
GenAddr bool
|
||||
UseSeed bool
|
||||
SeedNode string
|
||||
SecretFile string
|
||||
ExportDir string
|
||||
NonInteractive bool
|
||||
|
|
@ -111,12 +111,12 @@ func Init() {
|
|||
flag.StringVar(&OutboundPort, "port", "30303", "listening port")
|
||||
flag.BoolVar(&UseUPnP, "upnp", true, "enable UPnP support")
|
||||
flag.IntVar(&MaxPeer, "maxpeer", 30, "maximum desired peers")
|
||||
flag.IntVar(&RpcPort, "rpcport", 8080, "port to start json-rpc server on")
|
||||
flag.IntVar(&RpcPort, "rpcport", 8545, "port to start json-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(&StartWebSockets, "ws", false, "start websocket server")
|
||||
flag.BoolVar(&NonInteractive, "y", false, "non-interactive mode (say yes to confirmations)")
|
||||
flag.BoolVar(&UseSeed, "seed", true, "seed peers")
|
||||
flag.StringVar(&SeedNode, "seednode", "poc-8.ethdev.com:30303", "ip:port of seed node to connect to. Set to blank for skip")
|
||||
flag.BoolVar(&GenAddr, "genaddr", false, "create a new priv/pub key")
|
||||
flag.StringVar(&NatType, "nat", "", "NAT support (UPNP|PMP) (none)")
|
||||
flag.StringVar(&SecretFile, "import", "", "imports the file given (hex or mnemonic formats)")
|
||||
|
|
|
|||
|
|
@ -84,7 +84,7 @@ func run() error {
|
|||
utils.RegisterInterrupt(func(os.Signal) {
|
||||
gui.Stop()
|
||||
})
|
||||
go utils.StartEthereum(ethereum, UseSeed)
|
||||
go utils.StartEthereum(ethereum, SeedNode)
|
||||
|
||||
fmt.Println("ETH stack took", time.Since(tstart))
|
||||
|
||||
|
|
|
|||
|
|
@ -136,7 +136,7 @@ func (ui *UiLib) Muted(content string) {
|
|||
|
||||
func (ui *UiLib) Connect(button qml.Object) {
|
||||
if !ui.connected {
|
||||
ui.eth.Start(true)
|
||||
ui.eth.Start(SeedNode)
|
||||
ui.connected = true
|
||||
button.Set("enabled", false)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -121,9 +121,9 @@ func exit(err error) {
|
|||
os.Exit(status)
|
||||
}
|
||||
|
||||
func StartEthereum(ethereum *eth.Ethereum, UseSeed bool) {
|
||||
func StartEthereum(ethereum *eth.Ethereum, SeedNode string) {
|
||||
clilogger.Infof("Starting %s", ethereum.ClientIdentity())
|
||||
err := ethereum.Start(UseSeed)
|
||||
err := ethereum.Start(SeedNode)
|
||||
if err != nil {
|
||||
exit(err)
|
||||
}
|
||||
|
|
@ -205,7 +205,7 @@ func StartWebSockets(eth *eth.Ethereum, wsPort int) {
|
|||
clilogger.Infoln("Starting WebSockets")
|
||||
|
||||
var err error
|
||||
eth.WsServer, err = rpcws.NewWebSocketServer(eth, wsPort)
|
||||
eth.WsServer, err = rpcws.NewWebSocketServer(xeth.New(eth), wsPort)
|
||||
if err != nil {
|
||||
clilogger.Errorf("Could not start RPC interface (port %v): %v", wsPort, err)
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -1,98 +0,0 @@
|
|||
/*
|
||||
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)
|
||||
}
|
||||
|
|
@ -19,6 +19,10 @@ import (
|
|||
"gopkg.in/fatih/set.v0"
|
||||
)
|
||||
|
||||
type PendingBlockEvent struct {
|
||||
Block *types.Block
|
||||
}
|
||||
|
||||
var statelogger = logger.NewLogger("BLOCK")
|
||||
|
||||
type EthManager interface {
|
||||
|
|
@ -84,6 +88,37 @@ func (sm *BlockProcessor) TransitionState(statedb *state.StateDB, parent, block
|
|||
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) {
|
||||
var (
|
||||
receipts types.Receipts
|
||||
|
|
@ -96,15 +131,10 @@ func (self *BlockProcessor) ApplyTransactions(coinbase *state.StateObject, state
|
|||
|
||||
done:
|
||||
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()
|
||||
receipt, txGas, err := self.ApplyTransaction(coinbase, state, block, tx, totalUsedGas, transientProcess)
|
||||
if err != nil {
|
||||
return nil, nil, nil, nil, err
|
||||
|
||||
switch {
|
||||
case IsNonceErr(err):
|
||||
err = nil // ignore error
|
||||
|
|
@ -119,57 +149,41 @@ done:
|
|||
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)
|
||||
handled = append(handled, tx)
|
||||
|
||||
if ethutil.Config.Diff && ethutil.Config.DiffType == "all" {
|
||||
state.CreateOutputForDiff()
|
||||
}
|
||||
cumulativeSum.Add(cumulativeSum, new(big.Int).Mul(txGas, tx.GasPrice()))
|
||||
}
|
||||
|
||||
block.Reward = cumulativeSum
|
||||
block.Header().GasUsed = totalUsedGas
|
||||
|
||||
if transientProcess {
|
||||
go self.eventMux.Post(PendingBlockEvent{block})
|
||||
}
|
||||
|
||||
return receipts, handled, unhandled, erroneous, err
|
||||
}
|
||||
|
||||
func (sm *BlockProcessor) Process(block *types.Block) (td *big.Int, msgs state.Messages, err error) {
|
||||
func (sm *BlockProcessor) Process(block *types.Block) (td *big.Int, err error) {
|
||||
// Processing a blocks may never happen simultaneously
|
||||
sm.mutex.Lock()
|
||||
defer sm.mutex.Unlock()
|
||||
|
||||
header := block.Header()
|
||||
if sm.bc.HasBlock(header.Hash()) {
|
||||
return nil, nil, &KnownBlockError{header.Number, header.Hash()}
|
||||
return nil, &KnownBlockError{header.Number, header.Hash()}
|
||||
}
|
||||
|
||||
if !sm.bc.HasBlock(header.ParentHash) {
|
||||
return nil, nil, ParentError(header.ParentHash)
|
||||
return nil, ParentError(header.ParentHash)
|
||||
}
|
||||
parent := sm.bc.GetBlock(header.ParentHash)
|
||||
|
||||
return sm.ProcessWithParent(block, parent)
|
||||
}
|
||||
|
||||
func (sm *BlockProcessor) ProcessWithParent(block, parent *types.Block) (td *big.Int, messages state.Messages, err error) {
|
||||
func (sm *BlockProcessor) ProcessWithParent(block, parent *types.Block) (td *big.Int, err error) {
|
||||
sm.lastAttemptedBlock = block
|
||||
|
||||
state := state.New(parent.Root(), sm.db)
|
||||
|
|
@ -206,7 +220,7 @@ func (sm *BlockProcessor) ProcessWithParent(block, parent *types.Block) (td *big
|
|||
return
|
||||
}
|
||||
|
||||
if err = sm.AccumelateRewards(state, block, parent); err != nil {
|
||||
if err = sm.AccumulateRewards(state, block, parent); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
|
|
@ -219,11 +233,10 @@ func (sm *BlockProcessor) ProcessWithParent(block, parent *types.Block) (td *big
|
|||
|
||||
// Calculate the td for this block
|
||||
td = CalculateTD(block, parent)
|
||||
// Sync the current block's state to the database and cancelling out the deferred Undo
|
||||
// Sync the current block's state to the database
|
||||
state.Sync()
|
||||
// Set the block hashes for the current messages
|
||||
state.Manifest().SetHash(block.Hash())
|
||||
messages = state.Manifest().Messages
|
||||
// Reset the manifest XXX We need this?
|
||||
state.Manifest().Reset()
|
||||
// Remove transactions from the pool
|
||||
|
|
@ -231,7 +244,7 @@ func (sm *BlockProcessor) ProcessWithParent(block, parent *types.Block) (td *big
|
|||
|
||||
chainlogger.Infof("processed block #%d (%x...)\n", header.Number, block.Hash()[0:4])
|
||||
|
||||
return td, messages, nil
|
||||
return td, nil
|
||||
}
|
||||
|
||||
// Validates the current block. Returns an error if the block was invalid,
|
||||
|
|
@ -248,8 +261,8 @@ func (sm *BlockProcessor) ValidateBlock(block, parent *types.Block) error {
|
|||
}
|
||||
|
||||
diff := 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 diff <= 0 {
|
||||
return ValidationError("Block timestamp not after prev block %v (%v - %v)", diff, block.Header().Time, sm.bc.CurrentBlock().Header().Time)
|
||||
}
|
||||
|
||||
if block.Time() > time.Now().Unix() {
|
||||
|
|
@ -264,7 +277,7 @@ func (sm *BlockProcessor) ValidateBlock(block, parent *types.Block) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func (sm *BlockProcessor) AccumelateRewards(statedb *state.StateDB, block, parent *types.Block) error {
|
||||
func (sm *BlockProcessor) AccumulateRewards(statedb *state.StateDB, block, parent *types.Block) error {
|
||||
reward := new(big.Int).Set(BlockReward)
|
||||
|
||||
ancestors := set.New()
|
||||
|
|
@ -285,6 +298,10 @@ func (sm *BlockProcessor) AccumelateRewards(statedb *state.StateDB, block, paren
|
|||
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.Mul(BlockReward, big.NewInt(15)).Div(r, big.NewInt(16))
|
||||
|
||||
|
|
@ -299,14 +316,6 @@ func (sm *BlockProcessor) AccumelateRewards(statedb *state.StateDB, block, paren
|
|||
// Reward amount of ether to the coinbase address
|
||||
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
|
||||
}
|
||||
|
||||
|
|
@ -326,7 +335,7 @@ func (sm *BlockProcessor) GetMessages(block *types.Block) (messages []*state.Mes
|
|||
defer state.Reset()
|
||||
|
||||
sm.TransitionState(state, parent, block)
|
||||
sm.AccumelateRewards(state, block, parent)
|
||||
sm.AccumulateRewards(state, block, parent)
|
||||
|
||||
return state.Manifest().Messages, nil
|
||||
}
|
||||
|
|
@ -347,7 +356,7 @@ func (sm *BlockProcessor) GetLogs(block *types.Block) (logs state.Logs, err erro
|
|||
defer state.Reset()
|
||||
|
||||
sm.TransitionState(state, parent, block)
|
||||
sm.AccumelateRewards(state, block, parent)
|
||||
sm.AccumulateRewards(state, block, parent)
|
||||
|
||||
return state.Logs(), nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -359,7 +359,7 @@ func (bc *ChainManager) Stop() {
|
|||
|
||||
func (self *ChainManager) InsertChain(chain types.Blocks) error {
|
||||
for _, block := range chain {
|
||||
td, messages, err := self.processor.Process(block)
|
||||
td, err := self.processor.Process(block)
|
||||
if err != nil {
|
||||
if IsKnownBlockErr(err) {
|
||||
continue
|
||||
|
|
@ -391,7 +391,6 @@ func (self *ChainManager) InsertChain(chain types.Blocks) error {
|
|||
self.mu.Unlock()
|
||||
|
||||
self.eventMux.Post(NewBlockEvent{block})
|
||||
self.eventMux.Post(messages)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
|
|||
|
|
@ -33,8 +33,7 @@ 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) {
|
||||
env := self.env
|
||||
evm := vm.New(env)
|
||||
|
||||
evm := vm.NewVm(env)
|
||||
if env.Depth() == vm.MaxCallDepth {
|
||||
caller.ReturnGas(self.Gas, self.price)
|
||||
|
||||
|
|
|
|||
|
|
@ -33,8 +33,9 @@ type Filter struct {
|
|||
max int
|
||||
topics [][]byte
|
||||
|
||||
BlockCallback func(*types.Block)
|
||||
LogsCallback func(state.Logs)
|
||||
BlockCallback func(*types.Block)
|
||||
PendingCallback func(*types.Block)
|
||||
LogsCallback func(state.Logs)
|
||||
}
|
||||
|
||||
// Create a new filter which uses a bloom filter on blocks to figure out whether a particular block
|
||||
|
|
@ -128,28 +129,30 @@ func (self *Filter) Find() state.Logs {
|
|||
return logs[skip:]
|
||||
}
|
||||
|
||||
func includes(addresses [][]byte, a []byte) (found bool) {
|
||||
func includes(addresses [][]byte, a []byte) bool {
|
||||
for _, addr := range addresses {
|
||||
if bytes.Compare(addr, a) == 0 {
|
||||
return true
|
||||
if !bytes.Equal(addr, a) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
return true
|
||||
}
|
||||
|
||||
func (self *Filter) FilterLogs(logs state.Logs) state.Logs {
|
||||
var ret state.Logs
|
||||
|
||||
// Filter the logs for interesting stuff
|
||||
Logs:
|
||||
for _, log := range logs {
|
||||
if len(self.address) > 0 && !bytes.Equal(self.address, log.Address()) {
|
||||
continue
|
||||
}
|
||||
|
||||
for _, topic := range self.topics {
|
||||
if !includes(log.Topics(), topic) {
|
||||
continue
|
||||
max := int(math.Min(float64(len(self.topics)), float64(len(log.Topics()))))
|
||||
for i := 0; i < max; i++ {
|
||||
if !bytes.Equal(log.Topics()[i], self.topics[i]) {
|
||||
continue Logs
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -32,7 +32,6 @@ func GenesisBlock(db ethutil.Database) *types.Block {
|
|||
genesis.SetReceipts(types.Receipts{})
|
||||
|
||||
statedb := state.New(genesis.Root(), db)
|
||||
//statedb := state.New(genesis.Trie())
|
||||
for _, addr := range []string{
|
||||
"dbdbdb2cbd23b783741e8d7fcf51e459b497e4a6",
|
||||
"e4157b34ea9615cfbde6b4fda419828124b70c78",
|
||||
|
|
|
|||
|
|
@ -10,6 +10,8 @@ import (
|
|||
"github.com/ethereum/go-ethereum/vm"
|
||||
)
|
||||
|
||||
const tryJit = false
|
||||
|
||||
/*
|
||||
* The State transitioning model
|
||||
*
|
||||
|
|
@ -184,6 +186,7 @@ func (self *StateTransition) TransitionState() (ret []byte, err error) {
|
|||
return
|
||||
}
|
||||
|
||||
//stateCopy := self.env.State().Copy()
|
||||
vmenv := self.env
|
||||
var ref vm.ContextRef
|
||||
if MessageCreatesContract(msg) {
|
||||
|
|
@ -196,8 +199,34 @@ func (self *StateTransition) TransitionState() (ret []byte, err error) {
|
|||
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 {
|
||||
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 {
|
||||
|
|
|
|||
|
|
@ -6,7 +6,6 @@ import (
|
|||
"math/big"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"github.com/ethereum/go-ethereum/crypto"
|
||||
"github.com/ethereum/go-ethereum/ethutil"
|
||||
"github.com/ethereum/go-ethereum/rlp"
|
||||
|
|
@ -146,6 +145,10 @@ func (self *Block) SetTransactions(transactions Transactions) {
|
|||
self.transactions = 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 {
|
||||
return self.receipts
|
||||
|
|
@ -156,6 +159,10 @@ func (self *Block) SetReceipts(receipts Receipts) {
|
|||
self.header.ReceiptHash = DeriveSha(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{} {
|
||||
return []interface{}{self.header, self.transactions, self.uncles}
|
||||
|
|
@ -166,16 +173,13 @@ func (self *Block) RlpDataForStorage() interface{} {
|
|||
}
|
||||
|
||||
// Header accessors (add as you need them)
|
||||
func (self *Block) Number() *big.Int { return self.header.Number }
|
||||
func (self *Block) NumberU64() uint64 { return self.header.Number.Uint64() }
|
||||
func (self *Block) Bloom() []byte { return self.header.Bloom }
|
||||
func (self *Block) Coinbase() []byte { return self.header.Coinbase }
|
||||
func (self *Block) Time() int64 { return int64(self.header.Time) }
|
||||
func (self *Block) GasLimit() *big.Int { return self.header.GasLimit }
|
||||
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) Number() *big.Int { return self.header.Number }
|
||||
func (self *Block) NumberU64() uint64 { return self.header.Number.Uint64() }
|
||||
func (self *Block) Bloom() []byte { return self.header.Bloom }
|
||||
func (self *Block) Coinbase() []byte { return self.header.Coinbase }
|
||||
func (self *Block) Time() int64 { return int64(self.header.Time) }
|
||||
func (self *Block) GasLimit() *big.Int { return self.header.GasLimit }
|
||||
func (self *Block) GasUsed() *big.Int { return self.header.GasUsed }
|
||||
func (self *Block) Root() []byte { return self.header.Root }
|
||||
func (self *Block) SetRoot(root []byte) { self.header.Root = root }
|
||||
func (self *Block) Size() ethutil.StorageSize { return ethutil.StorageSize(len(ethutil.Encode(self))) }
|
||||
|
|
|
|||
|
|
@ -1,11 +1,7 @@
|
|||
package types
|
||||
|
||||
import (
|
||||
"math/big"
|
||||
|
||||
"github.com/ethereum/go-ethereum/state"
|
||||
)
|
||||
import "math/big"
|
||||
|
||||
type BlockProcessor interface {
|
||||
Process(*Block) (*big.Int, state.Messages, error)
|
||||
Process(*Block) (*big.Int, error)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ type VMEnv struct {
|
|||
msg Message
|
||||
depth int
|
||||
chain *ChainManager
|
||||
typ vm.Type
|
||||
}
|
||||
|
||||
func NewEnv(state *state.StateDB, chain *ChainManager, msg Message, block *types.Block) *VMEnv {
|
||||
|
|
@ -22,6 +23,7 @@ func NewEnv(state *state.StateDB, chain *ChainManager, msg Message, block *types
|
|||
state: state,
|
||||
block: block,
|
||||
msg: msg,
|
||||
typ: vm.StdVmTy,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -35,6 +37,8 @@ func (self *VMEnv) Value() *big.Int { return self.msg.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) VmType() vm.Type { return self.typ }
|
||||
func (self *VMEnv) SetVmType(t vm.Type) { self.typ = t }
|
||||
func (self *VMEnv) GetHash(n uint64) []byte {
|
||||
if block := self.chain.GetBlockByNumber(n); block != nil {
|
||||
return block.Hash()
|
||||
|
|
|
|||
|
|
@ -17,10 +17,6 @@ import (
|
|||
"github.com/ethereum/go-ethereum/whisper"
|
||||
)
|
||||
|
||||
const (
|
||||
seedNodeAddress = "poc-8.ethdev.com:30303"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Name string
|
||||
Version string
|
||||
|
|
@ -141,14 +137,13 @@ func New(config *Config) (*Ethereum, error) {
|
|||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
fmt.Println(nat)
|
||||
|
||||
eth.net = &p2p.Server{
|
||||
Identity: clientId,
|
||||
MaxPeers: config.MaxPeers,
|
||||
Protocols: protocols,
|
||||
Blacklist: eth.blacklist,
|
||||
NAT: p2p.UPNP(),
|
||||
NAT: nat,
|
||||
NoDial: !config.Dial,
|
||||
}
|
||||
|
||||
|
|
@ -224,7 +219,7 @@ func (s *Ethereum) Coinbase() []byte {
|
|||
}
|
||||
|
||||
// Start the ethereum
|
||||
func (s *Ethereum) Start(seed bool) error {
|
||||
func (s *Ethereum) Start(seedNode string) error {
|
||||
err := s.net.Start()
|
||||
if err != nil {
|
||||
return err
|
||||
|
|
@ -247,9 +242,9 @@ func (s *Ethereum) Start(seed bool) error {
|
|||
go s.blockBroadcastLoop()
|
||||
|
||||
// TODO: read peers here
|
||||
if seed {
|
||||
logger.Infof("Connect to seed node %v", seedNodeAddress)
|
||||
if err := s.SuggestPeer(seedNodeAddress); err != nil {
|
||||
if len(seedNode) > 0 {
|
||||
logger.Infof("Connect to seed node %v", seedNode)
|
||||
if err := s.SuggestPeer(seedNode); err != nil {
|
||||
logger.Infoln(err)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -636,12 +636,12 @@ func (self *BlockPool) AddBlock(block *types.Block, peerId string) {
|
|||
|
||||
// validate block for PoW
|
||||
if !self.verifyPoW(block) {
|
||||
poolLogger.Warnf("invalid pow on block [%s] by peer %s", name(hash), peerId)
|
||||
poolLogger.Warnf("invalid pow on block [%s %v] by peer %s", name(hash), block.Number(), peerId)
|
||||
self.peerError(peerId, ErrInvalidPoW, "%x", hash)
|
||||
return
|
||||
}
|
||||
}
|
||||
poolLogger.Debugf("added block [%s] sent by peer %s", name(hash), peerId)
|
||||
poolLogger.DebugDetailf("added block [%s] sent by peer %s", name(hash), peerId)
|
||||
node.block = block
|
||||
node.blockBy = peerId
|
||||
|
||||
|
|
|
|||
|
|
@ -46,6 +46,7 @@ type ethProtocol struct {
|
|||
// used as an argument to EthProtocol
|
||||
type txPool interface {
|
||||
AddTransactions([]*types.Transaction)
|
||||
GetTransactions() types.Transactions
|
||||
}
|
||||
|
||||
type chainManager interface {
|
||||
|
|
@ -101,6 +102,7 @@ func runEthProtocol(txPool txPool, chainManager chainManager, blockPool blockPoo
|
|||
}
|
||||
err = self.handleStatus()
|
||||
if err == nil {
|
||||
self.propagateTxs()
|
||||
for {
|
||||
err = self.handle()
|
||||
if err != nil {
|
||||
|
|
@ -324,3 +326,13 @@ 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...))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -80,6 +80,8 @@ 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) {
|
||||
if self.getBlockHashes != nil {
|
||||
hashes = self.getBlockHashes(hash, amount)
|
||||
|
|
|
|||
|
|
@ -59,7 +59,7 @@ func (self *FilterManager) GetFilter(id int) *core.Filter {
|
|||
|
||||
func (self *FilterManager) filterLoop() {
|
||||
// Subscribe to events
|
||||
events := self.eventMux.Subscribe(core.NewBlockEvent{}, state.Messages(nil))
|
||||
events := self.eventMux.Subscribe(core.PendingBlockEvent{}, core.NewBlockEvent{}, state.Logs(nil))
|
||||
|
||||
out:
|
||||
for {
|
||||
|
|
@ -77,6 +77,15 @@ out:
|
|||
}
|
||||
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:
|
||||
self.filterMu.RLock()
|
||||
for _, filter := range self.filters {
|
||||
|
|
|
|||
|
|
@ -27,6 +27,3 @@ done
|
|||
|
||||
$GOROOT/bin/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
|
||||
|
|
|
|||
|
|
@ -184,9 +184,7 @@ func (self *Miner) mine() {
|
|||
block.Header().Extra = self.Extra
|
||||
|
||||
// Apply uncles
|
||||
if len(self.uncles) > 0 {
|
||||
block.SetUncles(self.uncles)
|
||||
}
|
||||
block.SetUncles(self.uncles)
|
||||
|
||||
parent := chainMan.GetBlock(block.ParentHash())
|
||||
coinbase := state.GetOrNewStateObject(block.Coinbase())
|
||||
|
|
@ -206,7 +204,7 @@ func (self *Miner) mine() {
|
|||
block.SetReceipts(receipts)
|
||||
|
||||
// Accumulate the rewards included for this block
|
||||
blockProcessor.AccumelateRewards(state, block, parent)
|
||||
blockProcessor.AccumulateRewards(state, block, parent)
|
||||
|
||||
state.Update(ethutil.Big0)
|
||||
block.SetRoot(state.Root())
|
||||
|
|
|
|||
169
miner/worker.go
Normal file
169
miner/worker.go
Normal file
|
|
@ -0,0 +1,169 @@
|
|||
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
|
||||
}
|
||||
|
|
@ -53,7 +53,6 @@ func (pow *EasyPow) Search(block pow.Block, stop <-chan struct{}) []byte {
|
|||
elapsed := time.Now().UnixNano() - start
|
||||
hashes := ((float64(1e9) / float64(elapsed)) * float64(i)) / 1000
|
||||
pow.HashRate = int64(hashes)
|
||||
powlogger.Infoln("Hashing @", pow.HashRate, "khash")
|
||||
|
||||
t = time.Now()
|
||||
}
|
||||
|
|
@ -83,7 +82,7 @@ func verify(hash []byte, diff *big.Int, nonce []byte) bool {
|
|||
sha.Write(d)
|
||||
|
||||
verification := new(big.Int).Div(ethutil.BigPow(2, 256), diff)
|
||||
res := ethutil.U256(ethutil.BigD(sha.Sum(nil)))
|
||||
res := ethutil.BigD(sha.Sum(nil))
|
||||
|
||||
return res.Cmp(verification) <= 0
|
||||
}
|
||||
|
|
|
|||
16
rpc/args.go
16
rpc/args.go
|
|
@ -37,16 +37,6 @@ type NewTxArgs struct {
|
|||
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 {
|
||||
Tx string `json:"tx"`
|
||||
}
|
||||
|
|
@ -214,7 +204,7 @@ type FilterOptions struct {
|
|||
Earliest int64
|
||||
Latest int64
|
||||
Address string
|
||||
Topics []string
|
||||
Topic []string
|
||||
Skip int
|
||||
Max int
|
||||
}
|
||||
|
|
@ -224,8 +214,8 @@ func toFilterOptions(options *FilterOptions) core.FilterOptions {
|
|||
opts.Earliest = options.Earliest
|
||||
opts.Latest = options.Latest
|
||||
opts.Address = fromHex(options.Address)
|
||||
opts.Topics = make([][]byte, len(options.Topics))
|
||||
for i, topic := range options.Topics {
|
||||
opts.Topics = make([][]byte, len(options.Topic))
|
||||
for i, topic := range options.Topic {
|
||||
opts.Topics[i] = fromHex(topic)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -84,27 +84,30 @@ func (s *RpcHttpServer) Start() {
|
|||
}
|
||||
|
||||
func (s *RpcHttpServer) apiHandler(api *rpc.EthereumApi) http.Handler {
|
||||
var jsonrpcver string = "2.0"
|
||||
fn := func(w http.ResponseWriter, req *http.Request) {
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
rpchttplogger.Debugln("Handling request")
|
||||
rpchttplogger.DebugDetailln("Handling request")
|
||||
|
||||
reqParsed, reqerr := JSON.ParseRequestBody(req)
|
||||
if reqerr != nil {
|
||||
JSON.Send(w, &rpc.RpcErrorResponse{JsonRpc: reqParsed.JsonRpc, ID: reqParsed.ID, Error: true, ErrorText: rpc.ErrorParseRequest})
|
||||
jsonerr := &rpc.RpcErrorObject{-32700, rpc.ErrorParseRequest}
|
||||
JSON.Send(w, &rpc.RpcErrorResponse{JsonRpc: jsonrpcver, ID: nil, Error: jsonerr})
|
||||
return
|
||||
}
|
||||
|
||||
var response interface{}
|
||||
reserr := api.GetRequestReply(&reqParsed, &response)
|
||||
if reserr != nil {
|
||||
rpchttplogger.Errorln(reserr)
|
||||
JSON.Send(w, &rpc.RpcErrorResponse{JsonRpc: reqParsed.JsonRpc, ID: reqParsed.ID, Error: true, ErrorText: reserr.Error()})
|
||||
rpchttplogger.Warnln(reserr)
|
||||
jsonerr := &rpc.RpcErrorObject{-32603, reserr.Error()}
|
||||
JSON.Send(w, &rpc.RpcErrorResponse{JsonRpc: jsonrpcver, ID: &reqParsed.ID, Error: jsonerr})
|
||||
return
|
||||
}
|
||||
|
||||
rpchttplogger.Debugf("Generated response: %T %s", response, response)
|
||||
JSON.Send(w, &rpc.RpcSuccessResponse{JsonRpc: reqParsed.JsonRpc, ID: reqParsed.ID, Error: false, Result: response})
|
||||
JSON.Send(w, &rpc.RpcSuccessResponse{JsonRpc: jsonrpcver, ID: reqParsed.ID, Result: response})
|
||||
}
|
||||
|
||||
return http.HandlerFunc(fn)
|
||||
|
|
|
|||
|
|
@ -33,25 +33,6 @@ const (
|
|||
ErrorDecodeArgs = "Error: Could not decode arguments"
|
||||
)
|
||||
|
||||
type ErrorResponse struct {
|
||||
Error bool `json:"error"`
|
||||
ErrorText string `json:"errorText"`
|
||||
}
|
||||
|
||||
type RpcSuccessResponse struct {
|
||||
ID int `json:"id"`
|
||||
JsonRpc string `json:"jsonrpc"`
|
||||
Error bool `json:"error"`
|
||||
Result interface{} `json:"result"`
|
||||
}
|
||||
|
||||
type RpcErrorResponse struct {
|
||||
ID int `json:"id"`
|
||||
JsonRpc string `json:"jsonrpc"`
|
||||
Error bool `json:"error"`
|
||||
ErrorText string `json:"errortext"`
|
||||
}
|
||||
|
||||
type RpcRequest struct {
|
||||
JsonRpc string `json:"jsonrpc"`
|
||||
ID int `json:"id"`
|
||||
|
|
@ -59,6 +40,24 @@ type RpcRequest struct {
|
|||
Params []json.RawMessage `json:"params"`
|
||||
}
|
||||
|
||||
type RpcSuccessResponse struct {
|
||||
ID int `json:"id"`
|
||||
JsonRpc string `json:"jsonrpc"`
|
||||
Result interface{} `json:"result"`
|
||||
}
|
||||
|
||||
type RpcErrorResponse struct {
|
||||
ID *int `json:"id"`
|
||||
JsonRpc string `json:"jsonrpc"`
|
||||
Error *RpcErrorObject `json:"error"`
|
||||
}
|
||||
|
||||
type RpcErrorObject struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
// Data interface{} `json:"data"`
|
||||
}
|
||||
|
||||
func NewErrorResponse(msg string) error {
|
||||
return errors.New(msg)
|
||||
}
|
||||
|
|
@ -217,6 +216,21 @@ func (req *RpcRequest) ToFilterArgs() (*FilterOptions, error) {
|
|||
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) {
|
||||
if len(req.Params) < 1 {
|
||||
return 0, NewErrorResponse(ErrorArguments)
|
||||
|
|
|
|||
|
|
@ -32,6 +32,7 @@ import (
|
|||
"sync"
|
||||
|
||||
"github.com/ethereum/go-ethereum/core"
|
||||
"github.com/ethereum/go-ethereum/core/types"
|
||||
"github.com/ethereum/go-ethereum/crypto"
|
||||
"github.com/ethereum/go-ethereum/ethdb"
|
||||
"github.com/ethereum/go-ethereum/ethutil"
|
||||
|
|
@ -40,6 +41,11 @@ import (
|
|||
"github.com/ethereum/go-ethereum/xeth"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultGasPrice = "10000000000000"
|
||||
defaultGas = "10000"
|
||||
)
|
||||
|
||||
type EthereumApi struct {
|
||||
xeth *xeth.XEth
|
||||
filterManager *filter.FilterManager
|
||||
|
|
@ -70,6 +76,7 @@ func NewEthereumApi(eth *xeth.XEth) *EthereumApi {
|
|||
func (self *EthereumApi) NewFilter(args *FilterOptions, reply *interface{}) error {
|
||||
var id int
|
||||
filter := core.NewFilter(self.xeth.Backend())
|
||||
filter.SetOptions(toFilterOptions(args))
|
||||
filter.LogsCallback = func(logs state.Logs) {
|
||||
self.logMut.Lock()
|
||||
defer self.logMut.Unlock()
|
||||
|
|
@ -82,6 +89,25 @@ func (self *EthereumApi) NewFilter(args *FilterOptions, reply *interface{}) erro
|
|||
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 {
|
||||
self.logMut.RLock()
|
||||
defer self.logMut.RUnlock()
|
||||
|
|
@ -115,10 +141,14 @@ func (p *EthereumApi) GetBlock(args *GetBlockArgs, reply *interface{}) error {
|
|||
}
|
||||
|
||||
func (p *EthereumApi) Transact(args *NewTxArgs, reply *interface{}) error {
|
||||
err := args.requirements()
|
||||
if err != nil {
|
||||
return err
|
||||
if len(args.Gas) == 0 {
|
||||
args.Gas = defaultGas
|
||||
}
|
||||
|
||||
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)
|
||||
*reply = result
|
||||
return nil
|
||||
|
|
@ -379,6 +409,12 @@ func (p *EthereumApi) GetRequestReply(req *RpcRequest, reply *interface{}) error
|
|||
return err
|
||||
}
|
||||
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":
|
||||
args, err := req.ToFilterChangedArgs()
|
||||
if err != nil {
|
||||
|
|
@ -386,7 +422,7 @@ func (p *EthereumApi) GetRequestReply(req *RpcRequest, reply *interface{}) error
|
|||
}
|
||||
return p.FilterChanged(args, reply)
|
||||
case "eth_gasPrice":
|
||||
*reply = "10000000000000"
|
||||
*reply = defaultGasPrice
|
||||
return nil
|
||||
case "web3_sha3":
|
||||
args, err := req.ToSha3Args()
|
||||
|
|
|
|||
|
|
@ -18,10 +18,11 @@ package rpc
|
|||
|
||||
import (
|
||||
"encoding/json"
|
||||
"github.com/ethereum/go-ethereum/logger"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"github.com/ethereum/go-ethereum/ethutil"
|
||||
"github.com/ethereum/go-ethereum/logger"
|
||||
"github.com/ethereum/go-ethereum/state"
|
||||
)
|
||||
|
||||
|
|
@ -36,7 +37,7 @@ func (self JsonWrapper) Send(writer io.Writer, v interface{}) (n int, err error)
|
|||
rpclogger.Fatalln("Error marshalling JSON", err)
|
||||
return 0, err
|
||||
}
|
||||
rpclogger.Infof("Sending payload: %s", payload)
|
||||
rpclogger.DebugDetailf("Sending payload: %s", payload)
|
||||
|
||||
return writer.Write(payload)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -22,35 +22,30 @@ import (
|
|||
"net/http"
|
||||
|
||||
"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/rpc"
|
||||
"github.com/ethereum/go-ethereum/xeth"
|
||||
)
|
||||
|
||||
var wslogger = logger.NewLogger("RPC-WS")
|
||||
var JSON rpc.JsonWrapper
|
||||
|
||||
type WebSocketServer struct {
|
||||
eth *eth.Ethereum
|
||||
filterManager *filter.FilterManager
|
||||
port int
|
||||
doneCh chan bool
|
||||
listener net.Listener
|
||||
pipe *xeth.XEth
|
||||
port int
|
||||
doneCh chan bool
|
||||
listener net.Listener
|
||||
}
|
||||
|
||||
func NewWebSocketServer(eth *eth.Ethereum, port int) (*WebSocketServer, error) {
|
||||
func NewWebSocketServer(pipe *xeth.XEth, port int) (*WebSocketServer, error) {
|
||||
sport := fmt.Sprintf(":%d", port)
|
||||
l, err := net.Listen("tcp", sport)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
filterManager := filter.NewFilterManager(eth.EventMux())
|
||||
go filterManager.Start()
|
||||
|
||||
return &WebSocketServer{eth,
|
||||
filterManager,
|
||||
return &WebSocketServer{
|
||||
pipe,
|
||||
port,
|
||||
make(chan bool),
|
||||
l,
|
||||
|
|
@ -75,7 +70,7 @@ func (self *WebSocketServer) Start() {
|
|||
wslogger.Infof("Starting RPC-WS server on port %d", self.port)
|
||||
go self.handlerLoop()
|
||||
|
||||
api := rpc.NewEthereumApi(xeth.New(self.eth))
|
||||
api := rpc.NewEthereumApi(self.pipe)
|
||||
h := self.apiHandler(api)
|
||||
http.Handle("/ws", h)
|
||||
|
||||
|
|
@ -96,27 +91,29 @@ func (s *WebSocketServer) apiHandler(api *rpc.EthereumApi) http.Handler {
|
|||
}
|
||||
|
||||
func sockHandler(api *rpc.EthereumApi) websocket.Handler {
|
||||
var jsonrpcver string = "2.0"
|
||||
fn := func(conn *websocket.Conn) {
|
||||
for {
|
||||
wslogger.Debugln("Handling request")
|
||||
var reqParsed rpc.RpcRequest
|
||||
|
||||
if err := websocket.JSON.Receive(conn, &reqParsed); err != nil {
|
||||
wslogger.Debugln(rpc.ErrorParseRequest)
|
||||
websocket.JSON.Send(conn, rpc.RpcErrorResponse{JsonRpc: reqParsed.JsonRpc, ID: reqParsed.ID, Error: true, ErrorText: rpc.ErrorParseRequest})
|
||||
jsonerr := &rpc.RpcErrorObject{-32700, rpc.ErrorParseRequest}
|
||||
JSON.Send(conn, &rpc.RpcErrorResponse{JsonRpc: jsonrpcver, ID: nil, Error: jsonerr})
|
||||
continue
|
||||
}
|
||||
|
||||
var response interface{}
|
||||
reserr := api.GetRequestReply(&reqParsed, &response)
|
||||
if reserr != nil {
|
||||
wslogger.Errorln(reserr)
|
||||
websocket.JSON.Send(conn, rpc.RpcErrorResponse{JsonRpc: reqParsed.JsonRpc, ID: reqParsed.ID, Error: true, ErrorText: reserr.Error()})
|
||||
wslogger.Warnln(reserr)
|
||||
jsonerr := &rpc.RpcErrorObject{-32603, reserr.Error()}
|
||||
JSON.Send(conn, &rpc.RpcErrorResponse{JsonRpc: jsonrpcver, ID: &reqParsed.ID, Error: jsonerr})
|
||||
continue
|
||||
}
|
||||
|
||||
wslogger.Debugf("Generated response: %T %s", response, response)
|
||||
websocket.JSON.Send(conn, rpc.RpcSuccessResponse{JsonRpc: reqParsed.JsonRpc, ID: reqParsed.ID, Error: false, Result: response})
|
||||
JSON.Send(conn, &rpc.RpcSuccessResponse{JsonRpc: jsonrpcver, ID: reqParsed.ID, Result: response})
|
||||
}
|
||||
}
|
||||
return websocket.Handler(fn)
|
||||
|
|
|
|||
|
|
@ -31,7 +31,7 @@ type StateDB struct {
|
|||
|
||||
// Create a new state from a given trie
|
||||
func New(root []byte, db ethutil.Database) *StateDB {
|
||||
trie := trie.New(root, db)
|
||||
trie := trie.New(ethutil.CopyBytes(root), db)
|
||||
return &StateDB{db: db, trie: trie, stateObjects: make(map[string]*StateObject), manifest: NewManifest(), refund: make(map[string]*big.Int)}
|
||||
}
|
||||
|
||||
|
|
@ -234,12 +234,9 @@ func (self *StateDB) Copy() *StateDB {
|
|||
}
|
||||
|
||||
func (self *StateDB) Set(state *StateDB) {
|
||||
if state == nil {
|
||||
panic("Tried setting 'state' to nil through 'Set'")
|
||||
}
|
||||
|
||||
self.trie = state.trie
|
||||
self.stateObjects = state.stateObjects
|
||||
|
||||
self.refund = state.refund
|
||||
self.logs = state.logs
|
||||
}
|
||||
|
|
|
|||
2
tests/files/.gitignore
vendored
2
tests/files/.gitignore
vendored
|
|
@ -1,4 +1,6 @@
|
|||
venv/
|
||||
*~
|
||||
*.swp
|
||||
*.swo
|
||||
.vagrant/
|
||||
client-tests.pem
|
||||
|
|
|
|||
|
|
@ -1,15 +1,15 @@
|
|||
{
|
||||
"genesis_rlp_hex": "f9012ef90129a00000000000000000000000000000000000000000000000000000000000000000a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347940000000000000000000000000000000000000000a0c67c70f5d7d3049337d1dcc0503a249881120019a8e7322774dbfe57b463718ca056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b840000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008302000080830f4240808080a004994f67dc55b09e814ab7ffc8df3686b4afb2bb53e60eae97ef043fe03fb829c0c0",
|
||||
"genesis_state_root": "c67c70f5d7d3049337d1dcc0503a249881120019a8e7322774dbfe57b463718c",
|
||||
"initial_alloc": {
|
||||
"51ba59315b3a95761d0863b05ccc7a7f54703d99": "1606938044258990275541962092341162602522202993782792835301376",
|
||||
"e4157b34ea9615cfbde6b4fda419828124b70c78": "1606938044258990275541962092341162602522202993782792835301376",
|
||||
"b9c015918bdaba24b4ff057a92a3873d6eb201be": "1606938044258990275541962092341162602522202993782792835301376",
|
||||
"6c386a4b26f73c802f34673f7248bb118f97424a": "1606938044258990275541962092341162602522202993782792835301376",
|
||||
"cd2a3d9f938e13cd947ec05abc7fe734df8dd826": "1606938044258990275541962092341162602522202993782792835301376",
|
||||
"2ef47100e0787b915105fd5e3f4ff6752079d5cb": "1606938044258990275541962092341162602522202993782792835301376",
|
||||
"e6716f9544a56c530d868e4bfbacb172315bdead": "1606938044258990275541962092341162602522202993782792835301376",
|
||||
"1a26338f0d905e295fccb71fa9ea849ffa12aaf4": "1606938044258990275541962092341162602522202993782792835301376"
|
||||
},
|
||||
"genesis_hash": "779b1b620b03c0fb24963e183d5e88e3dbe4484e3f6e2aa05942e3be7b48e179"
|
||||
"genesis_rlp_hex": "f9012ef90129a00000000000000000000000000000000000000000000000000000000000000000a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347940000000000000000000000000000000000000000a0156df8ef53c723b40f97aff55dd785489cae8b457495916147687746bd5ee077a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b840000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008302000080830f4240808080a004994f67dc55b09e814ab7ffc8df3686b4afb2bb53e60eae97ef043fe03fb829c0c0",
|
||||
"genesis_state_root": "156df8ef53c723b40f97aff55dd785489cae8b457495916147687746bd5ee077",
|
||||
"initial_alloc": {
|
||||
"dbdbdb2cbd23b783741e8d7fcf51e459b497e4a6": "1606938044258990275541962092341162602522202993782792835301376",
|
||||
"e4157b34ea9615cfbde6b4fda419828124b70c78": "1606938044258990275541962092341162602522202993782792835301376",
|
||||
"b9c015918bdaba24b4ff057a92a3873d6eb201be": "1606938044258990275541962092341162602522202993782792835301376",
|
||||
"6c386a4b26f73c802f34673f7248bb118f97424a": "1606938044258990275541962092341162602522202993782792835301376",
|
||||
"cd2a3d9f938e13cd947ec05abc7fe734df8dd826": "1606938044258990275541962092341162602522202993782792835301376",
|
||||
"2ef47100e0787b915105fd5e3f4ff6752079d5cb": "1606938044258990275541962092341162602522202993782792835301376",
|
||||
"e6716f9544a56c530d868e4bfbacb172315bdead": "1606938044258990275541962092341162602522202993782792835301376",
|
||||
"1a26338f0d905e295fccb71fa9ea849ffa12aaf4": "1606938044258990275541962092341162602522202993782792835301376"
|
||||
},
|
||||
"genesis_hash": "c9cb614fddd89b3bc6e2f0ed1f8e58e8a0d826612a607a6151be6f39c991a941"
|
||||
}
|
||||
|
|
|
|||
2189
tests/files/BlockchainTests/badBlockChain.json
Normal file
2189
tests/files/BlockchainTests/badBlockChain.json
Normal file
File diff suppressed because it is too large
Load diff
2189
tests/files/BlockchainTests/basicBlockChain.json
Normal file
2189
tests/files/BlockchainTests/basicBlockChain.json
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -1,4 +1,44 @@
|
|||
{
|
||||
"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" : {
|
||||
"env" : {
|
||||
"currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
|
||||
|
|
|
|||
|
|
@ -1,4 +1,44 @@
|
|||
{
|
||||
"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" : {
|
||||
"env" : {
|
||||
"currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
|
||||
|
|
|
|||
|
|
@ -191,6 +191,256 @@
|
|||
"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" : {
|
||||
"env" : {
|
||||
"currentCoinbase" : "a94f5374fce5edbc8e2a8697c15331677e6ebf0b",
|
||||
|
|
@ -231,6 +481,86 @@
|
|||
"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" : {
|
||||
"env" : {
|
||||
"currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
|
||||
|
|
@ -425,59 +755,5 @@
|
|||
"to" : "a94f5374fce5edbc8e2a8697c15331677e6ebf0b",
|
||||
"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"
|
||||
}
|
||||
}
|
||||
}
|
||||
17
tests/files/TransactionTests/tt10mbDataField.json
Normal file
17
tests/files/TransactionTests/tt10mbDataField.json
Normal file
File diff suppressed because one or more lines are too long
123
tests/files/TransactionTests/ttTransactionTest.json
Normal file
123
tests/files/TransactionTests/ttTransactionTest.json
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
{
|
||||
"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"
|
||||
}
|
||||
}
|
||||
46
tests/files/VMTests/RandomTests/201501221210PYTHON.json
Normal file
46
tests/files/VMTests/RandomTests/201501221210PYTHON.json
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
{
|
||||
"randomVMtest" : {
|
||||
"callcreates" : [
|
||||
],
|
||||
"env" : {
|
||||
"currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
|
||||
"currentDifficulty" : "115792089237316195423570985008687907853269984665640564039457584007913129639935",
|
||||
"currentGasLimit" : "1000000",
|
||||
"currentNumber" : "300",
|
||||
"currentTimestamp" : "2",
|
||||
"previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6"
|
||||
},
|
||||
"exec" : {
|
||||
"address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6",
|
||||
"caller" : "cd1722f3947def4cf144679da39c4c32bdc35681",
|
||||
"code" : "0x4443434242444143f23036517602323a",
|
||||
"data" : "0x",
|
||||
"gas" : "10000",
|
||||
"gasPrice" : "100000000000000",
|
||||
"origin" : "cd1722f3947def4cf144679da39c4c32bdc35681",
|
||||
"value" : "1000000000000000000"
|
||||
},
|
||||
"gas" : "9949",
|
||||
"logs" : [
|
||||
],
|
||||
"out" : "0x",
|
||||
"post" : {
|
||||
"0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : {
|
||||
"balance" : "1000000000000000000",
|
||||
"code" : "0x4443434242444143f23036517602323a",
|
||||
"nonce" : "0",
|
||||
"storage" : {
|
||||
}
|
||||
}
|
||||
},
|
||||
"pre" : {
|
||||
"0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : {
|
||||
"balance" : "1000000000000000000",
|
||||
"code" : "0x4443434242444143f23036517602323a",
|
||||
"nonce" : "0",
|
||||
"storage" : {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
31
tests/files/VMTests/RandomTests/201501221235PYTHON.json
Normal file
31
tests/files/VMTests/RandomTests/201501221235PYTHON.json
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
{
|
||||
"randomVMtest" : {
|
||||
"env" : {
|
||||
"currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
|
||||
"currentDifficulty" : "115792089237316195423570985008687907853269984665640564039457584007913129639935",
|
||||
"currentGasLimit" : "1000000",
|
||||
"currentNumber" : "300",
|
||||
"currentTimestamp" : "2",
|
||||
"previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6"
|
||||
},
|
||||
"exec" : {
|
||||
"address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6",
|
||||
"caller" : "cd1722f3947def4cf144679da39c4c32bdc35681",
|
||||
"code" : "0x4243424440414442f28755",
|
||||
"data" : "0x",
|
||||
"gas" : "10000",
|
||||
"gasPrice" : "100000000000000",
|
||||
"origin" : "cd1722f3947def4cf144679da39c4c32bdc35681",
|
||||
"value" : "1000000000000000000"
|
||||
},
|
||||
"pre" : {
|
||||
"0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : {
|
||||
"balance" : "1000000000000000000",
|
||||
"code" : "0x4243424440414442f28755",
|
||||
"nonce" : "0",
|
||||
"storage" : {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
31
tests/files/VMTests/RandomTests/201501221531CPPJIT.json
Normal file
31
tests/files/VMTests/RandomTests/201501221531CPPJIT.json
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
{
|
||||
"randomVMtest" : {
|
||||
"env" : {
|
||||
"currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
|
||||
"currentDifficulty" : "115792089237316195423570985008687907853269984665640564039457584007913129639935",
|
||||
"currentGasLimit" : "1000000",
|
||||
"currentNumber" : "300",
|
||||
"currentTimestamp" : "2",
|
||||
"previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6"
|
||||
},
|
||||
"exec" : {
|
||||
"address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6",
|
||||
"caller" : "cd1722f3947def4cf144679da39c4c32bdc35681",
|
||||
"code" : "0x44444442414260428d3469",
|
||||
"data" : "0x",
|
||||
"gas" : "10000",
|
||||
"gasPrice" : "100000000000000",
|
||||
"origin" : "cd1722f3947def4cf144679da39c4c32bdc35681",
|
||||
"value" : "1000000000000000000"
|
||||
},
|
||||
"pre" : {
|
||||
"0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : {
|
||||
"balance" : "1000000000000000000",
|
||||
"code" : "0x44444442414260428d3469",
|
||||
"nonce" : "0",
|
||||
"storage" : {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
31
tests/files/VMTests/RandomTests/201501221647PYTHON.json
Normal file
31
tests/files/VMTests/RandomTests/201501221647PYTHON.json
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
{
|
||||
"randomVMtest" : {
|
||||
"env" : {
|
||||
"currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
|
||||
"currentDifficulty" : "115792089237316195423570985008687907853269984665640564039457584007913129639935",
|
||||
"currentGasLimit" : "1000000",
|
||||
"currentNumber" : "300",
|
||||
"currentTimestamp" : "2",
|
||||
"previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6"
|
||||
},
|
||||
"exec" : {
|
||||
"address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6",
|
||||
"caller" : "cd1722f3947def4cf144679da39c4c32bdc35681",
|
||||
"code" : "0x414240414343414559f28e380a95027f55",
|
||||
"data" : "0x",
|
||||
"gas" : "10000",
|
||||
"gasPrice" : "100000000000000",
|
||||
"origin" : "cd1722f3947def4cf144679da39c4c32bdc35681",
|
||||
"value" : "1000000000000000000"
|
||||
},
|
||||
"pre" : {
|
||||
"0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : {
|
||||
"balance" : "1000000000000000000",
|
||||
"code" : "0x414240414343414559f28e380a95027f55",
|
||||
"nonce" : "0",
|
||||
"storage" : {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
31
tests/files/VMTests/RandomTests/201501221718CPPJIT.json
Normal file
31
tests/files/VMTests/RandomTests/201501221718CPPJIT.json
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
{
|
||||
"randomVMtest" : {
|
||||
"env" : {
|
||||
"currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
|
||||
"currentDifficulty" : "115792089237316195423570985008687907853269984665640564039457584007913129639935",
|
||||
"currentGasLimit" : "1000000",
|
||||
"currentNumber" : "300",
|
||||
"currentTimestamp" : "2",
|
||||
"previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6"
|
||||
},
|
||||
"exec" : {
|
||||
"address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6",
|
||||
"caller" : "cd1722f3947def4cf144679da39c4c32bdc35681",
|
||||
"code" : "0x404042f14503454050800b559a55",
|
||||
"data" : "0x",
|
||||
"gas" : "10000",
|
||||
"gasPrice" : "100000000000000",
|
||||
"origin" : "cd1722f3947def4cf144679da39c4c32bdc35681",
|
||||
"value" : "1000000000000000000"
|
||||
},
|
||||
"pre" : {
|
||||
"0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : {
|
||||
"balance" : "1000000000000000000",
|
||||
"code" : "0x404042f14503454050800b559a55",
|
||||
"nonce" : "0",
|
||||
"storage" : {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
46
tests/files/VMTests/RandomTests/201501222304PYTHON.json
Normal file
46
tests/files/VMTests/RandomTests/201501222304PYTHON.json
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
{
|
||||
"randomVMtest" : {
|
||||
"callcreates" : [
|
||||
],
|
||||
"env" : {
|
||||
"currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
|
||||
"currentDifficulty" : "115792089237316195423570985008687907853269984665640564039457584007913129639935",
|
||||
"currentGasLimit" : "1000000",
|
||||
"currentNumber" : "300",
|
||||
"currentTimestamp" : "2",
|
||||
"previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6"
|
||||
},
|
||||
"exec" : {
|
||||
"address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6",
|
||||
"caller" : "cd1722f3947def4cf144679da39c4c32bdc35681",
|
||||
"code" : "0x4340434243444542f2ff6b589855",
|
||||
"data" : "0x",
|
||||
"gas" : "10000",
|
||||
"gasPrice" : "100000000000000",
|
||||
"origin" : "cd1722f3947def4cf144679da39c4c32bdc35681",
|
||||
"value" : "1000000000000000000"
|
||||
},
|
||||
"gas" : "9962",
|
||||
"logs" : [
|
||||
],
|
||||
"out" : "0x",
|
||||
"post" : {
|
||||
"0000000000000000000000000000000000000000" : {
|
||||
"balance" : "1000000000000000000",
|
||||
"code" : "0x",
|
||||
"nonce" : "0",
|
||||
"storage" : {
|
||||
}
|
||||
}
|
||||
},
|
||||
"pre" : {
|
||||
"0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : {
|
||||
"balance" : "1000000000000000000",
|
||||
"code" : "0x4340434243444542f2ff6b589855",
|
||||
"nonce" : "0",
|
||||
"storage" : {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
31
tests/files/VMTests/RandomTests/201501222357PYTHON.json
Normal file
31
tests/files/VMTests/RandomTests/201501222357PYTHON.json
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
{
|
||||
"randomVMtest" : {
|
||||
"env" : {
|
||||
"currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
|
||||
"currentDifficulty" : "115792089237316195423570985008687907853269984665640564039457584007913129639935",
|
||||
"currentGasLimit" : "1000000",
|
||||
"currentNumber" : "300",
|
||||
"currentTimestamp" : "2",
|
||||
"previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6"
|
||||
},
|
||||
"exec" : {
|
||||
"address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6",
|
||||
"caller" : "cd1722f3947def4cf144679da39c4c32bdc35681",
|
||||
"code" : "0x4540454243414442f255",
|
||||
"data" : "0x",
|
||||
"gas" : "10000",
|
||||
"gasPrice" : "100000000000000",
|
||||
"origin" : "cd1722f3947def4cf144679da39c4c32bdc35681",
|
||||
"value" : "1000000000000000000"
|
||||
},
|
||||
"pre" : {
|
||||
"0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : {
|
||||
"balance" : "1000000000000000000",
|
||||
"code" : "0x4540454243414442f255",
|
||||
"nonce" : "0",
|
||||
"storage" : {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
31
tests/files/VMTests/RandomTests/201501230844PYTHON.json
Normal file
31
tests/files/VMTests/RandomTests/201501230844PYTHON.json
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
{
|
||||
"randomVMtest" : {
|
||||
"env" : {
|
||||
"currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
|
||||
"currentDifficulty" : "115792089237316195423570985008687907853269984665640564039457584007913129639935",
|
||||
"currentGasLimit" : "1000000",
|
||||
"currentNumber" : "300",
|
||||
"currentTimestamp" : "2",
|
||||
"previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6"
|
||||
},
|
||||
"exec" : {
|
||||
"address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6",
|
||||
"caller" : "cd1722f3947def4cf144679da39c4c32bdc35681",
|
||||
"code" : "0x4242434041414342f29a6e560b3763",
|
||||
"data" : "0x",
|
||||
"gas" : "10000",
|
||||
"gasPrice" : "100000000000000",
|
||||
"origin" : "cd1722f3947def4cf144679da39c4c32bdc35681",
|
||||
"value" : "1000000000000000000"
|
||||
},
|
||||
"pre" : {
|
||||
"0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : {
|
||||
"balance" : "1000000000000000000",
|
||||
"code" : "0x4242434041414342f29a6e560b3763",
|
||||
"nonce" : "0",
|
||||
"storage" : {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
46
tests/files/VMTests/RandomTests/201501231158PYTHON.json
Normal file
46
tests/files/VMTests/RandomTests/201501231158PYTHON.json
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
{
|
||||
"randomVMtest" : {
|
||||
"callcreates" : [
|
||||
],
|
||||
"env" : {
|
||||
"currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
|
||||
"currentDifficulty" : "115792089237316195423570985008687907853269984665640564039457584007913129639935",
|
||||
"currentGasLimit" : "1000000",
|
||||
"currentNumber" : "300",
|
||||
"currentTimestamp" : "2",
|
||||
"previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6"
|
||||
},
|
||||
"exec" : {
|
||||
"address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6",
|
||||
"caller" : "cd1722f3947def4cf144679da39c4c32bdc35681",
|
||||
"code" : "0x444443434243414483f278851155",
|
||||
"data" : "0x",
|
||||
"gas" : "10000",
|
||||
"gasPrice" : "100000000000000",
|
||||
"origin" : "cd1722f3947def4cf144679da39c4c32bdc35681",
|
||||
"value" : "1000000000000000000"
|
||||
},
|
||||
"gas" : "9951",
|
||||
"logs" : [
|
||||
],
|
||||
"out" : "0x",
|
||||
"post" : {
|
||||
"0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : {
|
||||
"balance" : "1000000000000000000",
|
||||
"code" : "0x444443434243414483f278851155",
|
||||
"nonce" : "0",
|
||||
"storage" : {
|
||||
}
|
||||
}
|
||||
},
|
||||
"pre" : {
|
||||
"0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : {
|
||||
"balance" : "1000000000000000000",
|
||||
"code" : "0x444443434243414483f278851155",
|
||||
"nonce" : "0",
|
||||
"storage" : {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
31
tests/files/VMTests/RandomTests/201502031248CPPJIT.json
Normal file
31
tests/files/VMTests/RandomTests/201502031248CPPJIT.json
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
{
|
||||
"randomVMtest" : {
|
||||
"env" : {
|
||||
"currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
|
||||
"currentDifficulty" : "115792089237316195423570985008687907853269984665640564039457584007913129639935",
|
||||
"currentGasLimit" : "1000000",
|
||||
"currentNumber" : "300",
|
||||
"currentTimestamp" : "2",
|
||||
"previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6"
|
||||
},
|
||||
"exec" : {
|
||||
"address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6",
|
||||
"caller" : "cd1722f3947def4cf144679da39c4c32bdc35681",
|
||||
"code" : "0x404544420855",
|
||||
"data" : "0x",
|
||||
"gas" : "10000",
|
||||
"gasPrice" : "100000000000000",
|
||||
"origin" : "cd1722f3947def4cf144679da39c4c32bdc35681",
|
||||
"value" : "1000000000000000000"
|
||||
},
|
||||
"pre" : {
|
||||
"0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : {
|
||||
"balance" : "1000000000000000000",
|
||||
"code" : "0x404544420855",
|
||||
"nonce" : "0",
|
||||
"storage" : {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
59
tests/files/VMTests/RandomTests/201502032117GO.json
Normal file
59
tests/files/VMTests/RandomTests/201502032117GO.json
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
{
|
||||
"randomVMtest" : {
|
||||
"callcreates" : [
|
||||
{
|
||||
"data" : "0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
|
||||
"destination" : "",
|
||||
"gasLimit" : "9872",
|
||||
"value" : "2"
|
||||
},
|
||||
{
|
||||
"data" : "0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
|
||||
"destination" : "",
|
||||
"gasLimit" : "9770",
|
||||
"value" : "9870"
|
||||
}
|
||||
],
|
||||
"env" : {
|
||||
"currentCoinbase" : "2adc25665018aa1fe0e6bc666dac8fc2697ff9ba",
|
||||
"currentDifficulty" : "115792089237316195423570985008687907853269984665640564039457584007913129639935",
|
||||
"currentGasLimit" : "1000000",
|
||||
"currentNumber" : "300",
|
||||
"currentTimestamp" : "2",
|
||||
"previousHash" : "5e20a0453cecd065ea59c37ac63e079ee08998b6045136a8ce6635c7912ec0b6"
|
||||
},
|
||||
"exec" : {
|
||||
"address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6",
|
||||
"caller" : "cd1722f3947def4cf144679da39c4c32bdc35681",
|
||||
"code" : "0x424443444243434383f0155af055",
|
||||
"data" : "0x",
|
||||
"gas" : "10000",
|
||||
"gasPrice" : "100000000000000",
|
||||
"origin" : "cd1722f3947def4cf144679da39c4c32bdc35681",
|
||||
"value" : "1000000000000000000"
|
||||
},
|
||||
"gas" : "9470",
|
||||
"logs" : [
|
||||
],
|
||||
"out" : "0x",
|
||||
"post" : {
|
||||
"0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : {
|
||||
"balance" : "999999999999990128",
|
||||
"code" : "0x424443444243434383f0155af055",
|
||||
"nonce" : "0",
|
||||
"storage" : {
|
||||
"0x945304eb96065b2a98b57a48a06ae28d285a71b5" : "0x02"
|
||||
}
|
||||
}
|
||||
},
|
||||
"pre" : {
|
||||
"0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : {
|
||||
"balance" : "1000000000000000000",
|
||||
"code" : "0x424443444243434383f0155af055",
|
||||
"nonce" : "0",
|
||||
"storage" : {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
9
tests/files/ansible/ec2-setup.yml
Normal file
9
tests/files/ansible/ec2-setup.yml
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
---
|
||||
- name: Provision EC2 instances
|
||||
hosts: local
|
||||
gather_facts: false
|
||||
roles:
|
||||
- ec2
|
||||
|
||||
tasks:
|
||||
- include: roles/ec2/tasks/setup.yml
|
||||
10
tests/files/ansible/ec2-terminate.yml
Normal file
10
tests/files/ansible/ec2-terminate.yml
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
---
|
||||
- name: Terminate all ec2 instances
|
||||
hosts: security_group_client-tests
|
||||
remote_user: ubuntu # private key defined via ansible.cfg
|
||||
gather_facts: false
|
||||
roles:
|
||||
- ec2
|
||||
|
||||
tasks:
|
||||
- include: roles/ec2/tasks/terminate.yml
|
||||
95
tests/files/ansible/ec2.ini
Normal file
95
tests/files/ansible/ec2.ini
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
# Ansible EC2 external inventory script settings
|
||||
#
|
||||
|
||||
[ec2]
|
||||
|
||||
# to talk to a private eucalyptus instance uncomment these lines
|
||||
# and edit edit eucalyptus_host to be the host name of your cloud controller
|
||||
#eucalyptus = True
|
||||
#eucalyptus_host = clc.cloud.domain.org
|
||||
|
||||
# AWS regions to make calls to. Set this to 'all' to make request to all regions
|
||||
# in AWS and merge the results together. Alternatively, set this to a comma
|
||||
# separated list of regions. E.g. 'us-east-1,us-west-1,us-west-2'
|
||||
regions = us-east-1
|
||||
regions_exclude = us-gov-west-1,cn-north-1
|
||||
|
||||
# When generating inventory, Ansible needs to know how to address a server.
|
||||
# Each EC2 instance has a lot of variables associated with it. Here is the list:
|
||||
# http://docs.pythonboto.org/en/latest/ref/ec2.html#module-boto.ec2.instance
|
||||
# Below are 2 variables that are used as the address of a server:
|
||||
# - destination_variable
|
||||
# - vpc_destination_variable
|
||||
|
||||
# This is the normal destination variable to use. If you are running Ansible
|
||||
# from outside EC2, then 'public_dns_name' makes the most sense. If you are
|
||||
# running Ansible from within EC2, then perhaps you want to use the internal
|
||||
# address, and should set this to 'private_dns_name'.
|
||||
destination_variable = public_dns_name
|
||||
|
||||
# For server inside a VPC, using DNS names may not make sense. When an instance
|
||||
# has 'subnet_id' set, this variable is used. If the subnet is public, setting
|
||||
# this to 'ip_address' will return the public IP address. For instances in a
|
||||
# private subnet, this should be set to 'private_ip_address', and Ansible must
|
||||
# be run from with EC2.
|
||||
vpc_destination_variable = ip_address
|
||||
|
||||
# To tag instances on EC2 with the resource records that point to them from
|
||||
# Route53, uncomment and set 'route53' to True.
|
||||
route53 = False
|
||||
|
||||
# To exclude RDS instances from the inventory, uncomment and set to False.
|
||||
#rds = False
|
||||
|
||||
# Additionally, you can specify the list of zones to exclude looking up in
|
||||
# 'route53_excluded_zones' as a comma-separated list.
|
||||
# route53_excluded_zones = samplezone1.com, samplezone2.com
|
||||
|
||||
# By default, only EC2 instances in the 'running' state are returned. Set
|
||||
# 'all_instances' to True to return all instances regardless of state.
|
||||
all_instances = False
|
||||
|
||||
# By default, only RDS instances in the 'available' state are returned. Set
|
||||
# 'all_rds_instances' to True return all RDS instances regardless of state.
|
||||
all_rds_instances = False
|
||||
|
||||
# API calls to EC2 are slow. For this reason, we cache the results of an API
|
||||
# call. Set this to the path you want cache files to be written to. Two files
|
||||
# will be written to this directory:
|
||||
# - ansible-ec2.cache
|
||||
# - ansible-ec2.index
|
||||
cache_path = ~/.ansible/tmp
|
||||
|
||||
# The number of seconds a cache file is considered valid. After this many
|
||||
# seconds, a new API call will be made, and the cache file will be updated.
|
||||
# To disable the cache, set this value to 0
|
||||
cache_max_age = 300
|
||||
|
||||
# Organize groups into a nested/hierarchy instead of a flat namespace.
|
||||
nested_groups = False
|
||||
|
||||
# If you only want to include hosts that match a certain regular expression
|
||||
# pattern_include = stage-*
|
||||
|
||||
# If you want to exclude any hosts that match a certain regular expression
|
||||
# pattern_exclude = stage-*
|
||||
|
||||
# Instance filters can be used to control which instances are retrieved for
|
||||
# inventory. For the full list of possible filters, please read the EC2 API
|
||||
# docs: http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeInstances.html#query-DescribeInstances-filters
|
||||
# Filters are key/value pairs separated by '=', to list multiple filters use
|
||||
# a list separated by commas. See examples below.
|
||||
|
||||
# Retrieve only instances with (key=value) env=stage tag
|
||||
# instance_filters = tag:env=stage
|
||||
|
||||
# Retrieve only instances with role=webservers OR role=dbservers tag
|
||||
# instance_filters = tag:role=webservers,tag:role=dbservers
|
||||
|
||||
# Retrieve only t1.micro instances OR instances with tag env=stage
|
||||
# instance_filters = instance-type=t1.micro,tag:env=stage
|
||||
|
||||
# You can use wildcards in filter values also. Below will list instances which
|
||||
# tag Name value matches webservers1*
|
||||
# (ex. webservers15, webservers1a, webservers123 etc)
|
||||
# instance_filters = tag:Name=webservers1*
|
||||
727
tests/files/ansible/ec2.py
Executable file
727
tests/files/ansible/ec2.py
Executable file
|
|
@ -0,0 +1,727 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
'''
|
||||
EC2 external inventory script
|
||||
=================================
|
||||
|
||||
Generates inventory that Ansible can understand by making API request to
|
||||
AWS EC2 using the Boto library.
|
||||
|
||||
NOTE: This script assumes Ansible is being executed where the environment
|
||||
variables needed for Boto have already been set:
|
||||
export AWS_ACCESS_KEY_ID='AK123'
|
||||
export AWS_SECRET_ACCESS_KEY='abc123'
|
||||
|
||||
This script also assumes there is an ec2.ini file alongside it. To specify a
|
||||
different path to ec2.ini, define the EC2_INI_PATH environment variable:
|
||||
|
||||
export EC2_INI_PATH=/path/to/my_ec2.ini
|
||||
|
||||
If you're using eucalyptus you need to set the above variables and
|
||||
you need to define:
|
||||
|
||||
export EC2_URL=http://hostname_of_your_cc:port/services/Eucalyptus
|
||||
|
||||
For more details, see: http://docs.pythonboto.org/en/latest/boto_config_tut.html
|
||||
|
||||
When run against a specific host, this script returns the following variables:
|
||||
- ec2_ami_launch_index
|
||||
- ec2_architecture
|
||||
- ec2_association
|
||||
- ec2_attachTime
|
||||
- ec2_attachment
|
||||
- ec2_attachmentId
|
||||
- ec2_client_token
|
||||
- ec2_deleteOnTermination
|
||||
- ec2_description
|
||||
- ec2_deviceIndex
|
||||
- ec2_dns_name
|
||||
- ec2_eventsSet
|
||||
- ec2_group_name
|
||||
- ec2_hypervisor
|
||||
- ec2_id
|
||||
- ec2_image_id
|
||||
- ec2_instanceState
|
||||
- ec2_instance_type
|
||||
- ec2_ipOwnerId
|
||||
- ec2_ip_address
|
||||
- ec2_item
|
||||
- ec2_kernel
|
||||
- ec2_key_name
|
||||
- ec2_launch_time
|
||||
- ec2_monitored
|
||||
- ec2_monitoring
|
||||
- ec2_networkInterfaceId
|
||||
- ec2_ownerId
|
||||
- ec2_persistent
|
||||
- ec2_placement
|
||||
- ec2_platform
|
||||
- ec2_previous_state
|
||||
- ec2_private_dns_name
|
||||
- ec2_private_ip_address
|
||||
- ec2_publicIp
|
||||
- ec2_public_dns_name
|
||||
- ec2_ramdisk
|
||||
- ec2_reason
|
||||
- ec2_region
|
||||
- ec2_requester_id
|
||||
- ec2_root_device_name
|
||||
- ec2_root_device_type
|
||||
- ec2_security_group_ids
|
||||
- ec2_security_group_names
|
||||
- ec2_shutdown_state
|
||||
- ec2_sourceDestCheck
|
||||
- ec2_spot_instance_request_id
|
||||
- ec2_state
|
||||
- ec2_state_code
|
||||
- ec2_state_reason
|
||||
- ec2_status
|
||||
- ec2_subnet_id
|
||||
- ec2_tenancy
|
||||
- ec2_virtualization_type
|
||||
- ec2_vpc_id
|
||||
|
||||
These variables are pulled out of a boto.ec2.instance object. There is a lack of
|
||||
consistency with variable spellings (camelCase and underscores) since this
|
||||
just loops through all variables the object exposes. It is preferred to use the
|
||||
ones with underscores when multiple exist.
|
||||
|
||||
In addition, if an instance has AWS Tags associated with it, each tag is a new
|
||||
variable named:
|
||||
- ec2_tag_[Key] = [Value]
|
||||
|
||||
Security groups are comma-separated in 'ec2_security_group_ids' and
|
||||
'ec2_security_group_names'.
|
||||
'''
|
||||
|
||||
# (c) 2012, Peter Sankauskas
|
||||
#
|
||||
# This file is part of Ansible,
|
||||
#
|
||||
# Ansible 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.
|
||||
#
|
||||
# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
######################################################################
|
||||
|
||||
import sys
|
||||
import os
|
||||
import argparse
|
||||
import re
|
||||
from time import time
|
||||
import boto
|
||||
from boto import ec2
|
||||
from boto import rds
|
||||
from boto import route53
|
||||
import ConfigParser
|
||||
from collections import defaultdict
|
||||
|
||||
try:
|
||||
import json
|
||||
except ImportError:
|
||||
import simplejson as json
|
||||
|
||||
|
||||
class Ec2Inventory(object):
|
||||
def _empty_inventory(self):
|
||||
return {"_meta" : {"hostvars" : {}}}
|
||||
|
||||
def __init__(self):
|
||||
''' Main execution path '''
|
||||
|
||||
# Inventory grouped by instance IDs, tags, security groups, regions,
|
||||
# and availability zones
|
||||
self.inventory = self._empty_inventory()
|
||||
|
||||
# Index of hostname (address) to instance ID
|
||||
self.index = {}
|
||||
|
||||
# Read settings and parse CLI arguments
|
||||
self.read_settings()
|
||||
self.parse_cli_args()
|
||||
|
||||
# Cache
|
||||
if self.args.refresh_cache:
|
||||
self.do_api_calls_update_cache()
|
||||
elif not self.is_cache_valid():
|
||||
self.do_api_calls_update_cache()
|
||||
|
||||
# Data to print
|
||||
if self.args.host:
|
||||
data_to_print = self.get_host_info()
|
||||
|
||||
elif self.args.list:
|
||||
# Display list of instances for inventory
|
||||
if self.inventory == self._empty_inventory():
|
||||
data_to_print = self.get_inventory_from_cache()
|
||||
else:
|
||||
data_to_print = self.json_format_dict(self.inventory, True)
|
||||
|
||||
print data_to_print
|
||||
|
||||
|
||||
def is_cache_valid(self):
|
||||
''' Determines if the cache files have expired, or if it is still valid '''
|
||||
|
||||
if os.path.isfile(self.cache_path_cache):
|
||||
mod_time = os.path.getmtime(self.cache_path_cache)
|
||||
current_time = time()
|
||||
if (mod_time + self.cache_max_age) > current_time:
|
||||
if os.path.isfile(self.cache_path_index):
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def read_settings(self):
|
||||
''' Reads the settings from the ec2.ini file '''
|
||||
|
||||
config = ConfigParser.SafeConfigParser()
|
||||
ec2_default_ini_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'ec2.ini')
|
||||
ec2_ini_path = os.environ.get('EC2_INI_PATH', ec2_default_ini_path)
|
||||
config.read(ec2_ini_path)
|
||||
|
||||
# is eucalyptus?
|
||||
self.eucalyptus_host = None
|
||||
self.eucalyptus = False
|
||||
if config.has_option('ec2', 'eucalyptus'):
|
||||
self.eucalyptus = config.getboolean('ec2', 'eucalyptus')
|
||||
if self.eucalyptus and config.has_option('ec2', 'eucalyptus_host'):
|
||||
self.eucalyptus_host = config.get('ec2', 'eucalyptus_host')
|
||||
|
||||
# Regions
|
||||
self.regions = []
|
||||
configRegions = config.get('ec2', 'regions')
|
||||
configRegions_exclude = config.get('ec2', 'regions_exclude')
|
||||
if (configRegions == 'all'):
|
||||
if self.eucalyptus_host:
|
||||
self.regions.append(boto.connect_euca(host=self.eucalyptus_host).region.name)
|
||||
else:
|
||||
for regionInfo in ec2.regions():
|
||||
if regionInfo.name not in configRegions_exclude:
|
||||
self.regions.append(regionInfo.name)
|
||||
else:
|
||||
self.regions = configRegions.split(",")
|
||||
|
||||
# Destination addresses
|
||||
self.destination_variable = config.get('ec2', 'destination_variable')
|
||||
self.vpc_destination_variable = config.get('ec2', 'vpc_destination_variable')
|
||||
|
||||
# Route53
|
||||
self.route53_enabled = config.getboolean('ec2', 'route53')
|
||||
self.route53_excluded_zones = []
|
||||
if config.has_option('ec2', 'route53_excluded_zones'):
|
||||
self.route53_excluded_zones.extend(
|
||||
config.get('ec2', 'route53_excluded_zones', '').split(','))
|
||||
|
||||
# Include RDS instances?
|
||||
self.rds_enabled = True
|
||||
if config.has_option('ec2', 'rds'):
|
||||
self.rds_enabled = config.getboolean('ec2', 'rds')
|
||||
|
||||
# Return all EC2 and RDS instances (if RDS is enabled)
|
||||
if config.has_option('ec2', 'all_instances'):
|
||||
self.all_instances = config.getboolean('ec2', 'all_instances')
|
||||
else:
|
||||
self.all_instances = False
|
||||
if config.has_option('ec2', 'all_rds_instances') and self.rds_enabled:
|
||||
self.all_rds_instances = config.getboolean('ec2', 'all_rds_instances')
|
||||
else:
|
||||
self.all_rds_instances = False
|
||||
|
||||
# Cache related
|
||||
cache_dir = os.path.expanduser(config.get('ec2', 'cache_path'))
|
||||
if not os.path.exists(cache_dir):
|
||||
os.makedirs(cache_dir)
|
||||
|
||||
self.cache_path_cache = cache_dir + "/ansible-ec2.cache"
|
||||
self.cache_path_index = cache_dir + "/ansible-ec2.index"
|
||||
self.cache_max_age = config.getint('ec2', 'cache_max_age')
|
||||
|
||||
# Configure nested groups instead of flat namespace.
|
||||
if config.has_option('ec2', 'nested_groups'):
|
||||
self.nested_groups = config.getboolean('ec2', 'nested_groups')
|
||||
else:
|
||||
self.nested_groups = False
|
||||
|
||||
# Do we need to just include hosts that match a pattern?
|
||||
try:
|
||||
pattern_include = config.get('ec2', 'pattern_include')
|
||||
if pattern_include and len(pattern_include) > 0:
|
||||
self.pattern_include = re.compile(pattern_include)
|
||||
else:
|
||||
self.pattern_include = None
|
||||
except ConfigParser.NoOptionError, e:
|
||||
self.pattern_include = None
|
||||
|
||||
# Do we need to exclude hosts that match a pattern?
|
||||
try:
|
||||
pattern_exclude = config.get('ec2', 'pattern_exclude');
|
||||
if pattern_exclude and len(pattern_exclude) > 0:
|
||||
self.pattern_exclude = re.compile(pattern_exclude)
|
||||
else:
|
||||
self.pattern_exclude = None
|
||||
except ConfigParser.NoOptionError, e:
|
||||
self.pattern_exclude = None
|
||||
|
||||
# Instance filters (see boto and EC2 API docs)
|
||||
self.ec2_instance_filters = defaultdict(list)
|
||||
if config.has_option('ec2', 'instance_filters'):
|
||||
for x in config.get('ec2', 'instance_filters', '').split(','):
|
||||
filter_key, filter_value = x.split('=')
|
||||
self.ec2_instance_filters[filter_key].append(filter_value)
|
||||
|
||||
def parse_cli_args(self):
|
||||
''' Command line argument processing '''
|
||||
|
||||
parser = argparse.ArgumentParser(description='Produce an Ansible Inventory file based on EC2')
|
||||
parser.add_argument('--list', action='store_true', default=True,
|
||||
help='List instances (default: True)')
|
||||
parser.add_argument('--host', action='store',
|
||||
help='Get all the variables about a specific instance')
|
||||
parser.add_argument('--refresh-cache', action='store_true', default=False,
|
||||
help='Force refresh of cache by making API requests to EC2 (default: False - use cache files)')
|
||||
self.args = parser.parse_args()
|
||||
|
||||
|
||||
def do_api_calls_update_cache(self):
|
||||
''' Do API calls to each region, and save data in cache files '''
|
||||
|
||||
if self.route53_enabled:
|
||||
self.get_route53_records()
|
||||
|
||||
for region in self.regions:
|
||||
self.get_instances_by_region(region)
|
||||
if self.rds_enabled:
|
||||
self.get_rds_instances_by_region(region)
|
||||
|
||||
self.write_to_cache(self.inventory, self.cache_path_cache)
|
||||
self.write_to_cache(self.index, self.cache_path_index)
|
||||
|
||||
|
||||
def get_instances_by_region(self, region):
|
||||
''' Makes an AWS EC2 API call to the list of instances in a particular
|
||||
region '''
|
||||
|
||||
try:
|
||||
if self.eucalyptus:
|
||||
conn = boto.connect_euca(host=self.eucalyptus_host)
|
||||
conn.APIVersion = '2010-08-31'
|
||||
else:
|
||||
conn = ec2.connect_to_region(region)
|
||||
|
||||
# connect_to_region will fail "silently" by returning None if the region name is wrong or not supported
|
||||
if conn is None:
|
||||
print("region name: %s likely not supported, or AWS is down. connection to region failed." % region)
|
||||
sys.exit(1)
|
||||
|
||||
reservations = []
|
||||
if self.ec2_instance_filters:
|
||||
for filter_key, filter_values in self.ec2_instance_filters.iteritems():
|
||||
reservations.extend(conn.get_all_instances(filters = { filter_key : filter_values }))
|
||||
else:
|
||||
reservations = conn.get_all_instances()
|
||||
|
||||
for reservation in reservations:
|
||||
for instance in reservation.instances:
|
||||
self.add_instance(instance, region)
|
||||
|
||||
except boto.exception.BotoServerError, e:
|
||||
if not self.eucalyptus:
|
||||
print "Looks like AWS is down again:"
|
||||
print e
|
||||
sys.exit(1)
|
||||
|
||||
def get_rds_instances_by_region(self, region):
|
||||
''' Makes an AWS API call to the list of RDS instances in a particular
|
||||
region '''
|
||||
|
||||
try:
|
||||
conn = rds.connect_to_region(region)
|
||||
if conn:
|
||||
instances = conn.get_all_dbinstances()
|
||||
for instance in instances:
|
||||
self.add_rds_instance(instance, region)
|
||||
except boto.exception.BotoServerError, e:
|
||||
if not e.reason == "Forbidden":
|
||||
print "Looks like AWS RDS is down: "
|
||||
print e
|
||||
sys.exit(1)
|
||||
|
||||
def get_instance(self, region, instance_id):
|
||||
''' Gets details about a specific instance '''
|
||||
if self.eucalyptus:
|
||||
conn = boto.connect_euca(self.eucalyptus_host)
|
||||
conn.APIVersion = '2010-08-31'
|
||||
else:
|
||||
conn = ec2.connect_to_region(region)
|
||||
|
||||
# connect_to_region will fail "silently" by returning None if the region name is wrong or not supported
|
||||
if conn is None:
|
||||
print("region name: %s likely not supported, or AWS is down. connection to region failed." % region)
|
||||
sys.exit(1)
|
||||
|
||||
reservations = conn.get_all_instances([instance_id])
|
||||
for reservation in reservations:
|
||||
for instance in reservation.instances:
|
||||
return instance
|
||||
|
||||
def add_instance(self, instance, region):
|
||||
''' Adds an instance to the inventory and index, as long as it is
|
||||
addressable '''
|
||||
|
||||
# Only want running instances unless all_instances is True
|
||||
if not self.all_instances and instance.state != 'running':
|
||||
return
|
||||
|
||||
# Select the best destination address
|
||||
if instance.subnet_id:
|
||||
dest = getattr(instance, self.vpc_destination_variable)
|
||||
else:
|
||||
dest = getattr(instance, self.destination_variable)
|
||||
|
||||
if not dest:
|
||||
# Skip instances we cannot address (e.g. private VPC subnet)
|
||||
return
|
||||
|
||||
# if we only want to include hosts that match a pattern, skip those that don't
|
||||
if self.pattern_include and not self.pattern_include.match(dest):
|
||||
return
|
||||
|
||||
# if we need to exclude hosts that match a pattern, skip those
|
||||
if self.pattern_exclude and self.pattern_exclude.match(dest):
|
||||
return
|
||||
|
||||
# Add to index
|
||||
self.index[dest] = [region, instance.id]
|
||||
|
||||
# Inventory: Group by instance ID (always a group of 1)
|
||||
self.inventory[instance.id] = [dest]
|
||||
if self.nested_groups:
|
||||
self.push_group(self.inventory, 'instances', instance.id)
|
||||
|
||||
# Inventory: Group by region
|
||||
if self.nested_groups:
|
||||
self.push_group(self.inventory, 'regions', region)
|
||||
else:
|
||||
self.push(self.inventory, region, dest)
|
||||
|
||||
# Inventory: Group by availability zone
|
||||
self.push(self.inventory, instance.placement, dest)
|
||||
if self.nested_groups:
|
||||
self.push_group(self.inventory, region, instance.placement)
|
||||
|
||||
# Inventory: Group by instance type
|
||||
type_name = self.to_safe('type_' + instance.instance_type)
|
||||
self.push(self.inventory, type_name, dest)
|
||||
if self.nested_groups:
|
||||
self.push_group(self.inventory, 'types', type_name)
|
||||
|
||||
# Inventory: Group by key pair
|
||||
if instance.key_name:
|
||||
key_name = self.to_safe('key_' + instance.key_name)
|
||||
self.push(self.inventory, key_name, dest)
|
||||
if self.nested_groups:
|
||||
self.push_group(self.inventory, 'keys', key_name)
|
||||
|
||||
# Inventory: Group by VPC
|
||||
if instance.vpc_id:
|
||||
self.push(self.inventory, self.to_safe('vpc_id_' + instance.vpc_id), dest)
|
||||
|
||||
# Inventory: Group by security group
|
||||
try:
|
||||
for group in instance.groups:
|
||||
key = self.to_safe("security_group_" + group.name)
|
||||
self.push(self.inventory, key, dest)
|
||||
if self.nested_groups:
|
||||
self.push_group(self.inventory, 'security_groups', key)
|
||||
except AttributeError:
|
||||
print 'Package boto seems a bit older.'
|
||||
print 'Please upgrade boto >= 2.3.0.'
|
||||
sys.exit(1)
|
||||
|
||||
# Inventory: Group by tag keys
|
||||
for k, v in instance.tags.iteritems():
|
||||
key = self.to_safe("tag_" + k + "=" + v)
|
||||
self.push(self.inventory, key, dest)
|
||||
if self.nested_groups:
|
||||
self.push_group(self.inventory, 'tags', self.to_safe("tag_" + k))
|
||||
self.push_group(self.inventory, self.to_safe("tag_" + k), key)
|
||||
|
||||
# Inventory: Group by Route53 domain names if enabled
|
||||
if self.route53_enabled:
|
||||
route53_names = self.get_instance_route53_names(instance)
|
||||
for name in route53_names:
|
||||
self.push(self.inventory, name, dest)
|
||||
if self.nested_groups:
|
||||
self.push_group(self.inventory, 'route53', name)
|
||||
|
||||
# Global Tag: instances without tags
|
||||
if len(instance.tags) == 0:
|
||||
self.push(self.inventory, 'tag_none', dest)
|
||||
|
||||
# Global Tag: tag all EC2 instances
|
||||
self.push(self.inventory, 'ec2', dest)
|
||||
|
||||
self.inventory["_meta"]["hostvars"][dest] = self.get_host_info_dict_from_instance(instance)
|
||||
|
||||
|
||||
def add_rds_instance(self, instance, region):
|
||||
''' Adds an RDS instance to the inventory and index, as long as it is
|
||||
addressable '''
|
||||
|
||||
# Only want available instances unless all_rds_instances is True
|
||||
if not self.all_rds_instances and instance.status != 'available':
|
||||
return
|
||||
|
||||
# Select the best destination address
|
||||
#if instance.subnet_id:
|
||||
#dest = getattr(instance, self.vpc_destination_variable)
|
||||
#else:
|
||||
#dest = getattr(instance, self.destination_variable)
|
||||
dest = instance.endpoint[0]
|
||||
|
||||
if not dest:
|
||||
# Skip instances we cannot address (e.g. private VPC subnet)
|
||||
return
|
||||
|
||||
# Add to index
|
||||
self.index[dest] = [region, instance.id]
|
||||
|
||||
# Inventory: Group by instance ID (always a group of 1)
|
||||
self.inventory[instance.id] = [dest]
|
||||
if self.nested_groups:
|
||||
self.push_group(self.inventory, 'instances', instance.id)
|
||||
|
||||
# Inventory: Group by region
|
||||
if self.nested_groups:
|
||||
self.push_group(self.inventory, 'regions', region)
|
||||
else:
|
||||
self.push(self.inventory, region, dest)
|
||||
|
||||
# Inventory: Group by availability zone
|
||||
self.push(self.inventory, instance.availability_zone, dest)
|
||||
if self.nested_groups:
|
||||
self.push_group(self.inventory, region, instance.availability_zone)
|
||||
|
||||
# Inventory: Group by instance type
|
||||
type_name = self.to_safe('type_' + instance.instance_class)
|
||||
self.push(self.inventory, type_name, dest)
|
||||
if self.nested_groups:
|
||||
self.push_group(self.inventory, 'types', type_name)
|
||||
|
||||
# Inventory: Group by security group
|
||||
try:
|
||||
if instance.security_group:
|
||||
key = self.to_safe("security_group_" + instance.security_group.name)
|
||||
self.push(self.inventory, key, dest)
|
||||
if self.nested_groups:
|
||||
self.push_group(self.inventory, 'security_groups', key)
|
||||
|
||||
except AttributeError:
|
||||
print 'Package boto seems a bit older.'
|
||||
print 'Please upgrade boto >= 2.3.0.'
|
||||
sys.exit(1)
|
||||
|
||||
# Inventory: Group by engine
|
||||
self.push(self.inventory, self.to_safe("rds_" + instance.engine), dest)
|
||||
if self.nested_groups:
|
||||
self.push_group(self.inventory, 'rds_engines', self.to_safe("rds_" + instance.engine))
|
||||
|
||||
# Inventory: Group by parameter group
|
||||
self.push(self.inventory, self.to_safe("rds_parameter_group_" + instance.parameter_group.name), dest)
|
||||
if self.nested_groups:
|
||||
self.push_group(self.inventory, 'rds_parameter_groups', self.to_safe("rds_parameter_group_" + instance.parameter_group.name))
|
||||
|
||||
# Global Tag: all RDS instances
|
||||
self.push(self.inventory, 'rds', dest)
|
||||
|
||||
self.inventory["_meta"]["hostvars"][dest] = self.get_host_info_dict_from_instance(instance)
|
||||
|
||||
|
||||
def get_route53_records(self):
|
||||
''' Get and store the map of resource records to domain names that
|
||||
point to them. '''
|
||||
|
||||
r53_conn = route53.Route53Connection()
|
||||
all_zones = r53_conn.get_zones()
|
||||
|
||||
route53_zones = [ zone for zone in all_zones if zone.name[:-1]
|
||||
not in self.route53_excluded_zones ]
|
||||
|
||||
self.route53_records = {}
|
||||
|
||||
for zone in route53_zones:
|
||||
rrsets = r53_conn.get_all_rrsets(zone.id)
|
||||
|
||||
for record_set in rrsets:
|
||||
record_name = record_set.name
|
||||
|
||||
if record_name.endswith('.'):
|
||||
record_name = record_name[:-1]
|
||||
|
||||
for resource in record_set.resource_records:
|
||||
self.route53_records.setdefault(resource, set())
|
||||
self.route53_records[resource].add(record_name)
|
||||
|
||||
|
||||
def get_instance_route53_names(self, instance):
|
||||
''' Check if an instance is referenced in the records we have from
|
||||
Route53. If it is, return the list of domain names pointing to said
|
||||
instance. If nothing points to it, return an empty list. '''
|
||||
|
||||
instance_attributes = [ 'public_dns_name', 'private_dns_name',
|
||||
'ip_address', 'private_ip_address' ]
|
||||
|
||||
name_list = set()
|
||||
|
||||
for attrib in instance_attributes:
|
||||
try:
|
||||
value = getattr(instance, attrib)
|
||||
except AttributeError:
|
||||
continue
|
||||
|
||||
if value in self.route53_records:
|
||||
name_list.update(self.route53_records[value])
|
||||
|
||||
return list(name_list)
|
||||
|
||||
|
||||
def get_host_info_dict_from_instance(self, instance):
|
||||
instance_vars = {}
|
||||
for key in vars(instance):
|
||||
value = getattr(instance, key)
|
||||
key = self.to_safe('ec2_' + key)
|
||||
|
||||
# Handle complex types
|
||||
# state/previous_state changed to properties in boto in https://github.com/boto/boto/commit/a23c379837f698212252720d2af8dec0325c9518
|
||||
if key == 'ec2__state':
|
||||
instance_vars['ec2_state'] = instance.state or ''
|
||||
instance_vars['ec2_state_code'] = instance.state_code
|
||||
elif key == 'ec2__previous_state':
|
||||
instance_vars['ec2_previous_state'] = instance.previous_state or ''
|
||||
instance_vars['ec2_previous_state_code'] = instance.previous_state_code
|
||||
elif type(value) in [int, bool]:
|
||||
instance_vars[key] = value
|
||||
elif type(value) in [str, unicode]:
|
||||
instance_vars[key] = value.strip()
|
||||
elif type(value) == type(None):
|
||||
instance_vars[key] = ''
|
||||
elif key == 'ec2_region':
|
||||
instance_vars[key] = value.name
|
||||
elif key == 'ec2__placement':
|
||||
instance_vars['ec2_placement'] = value.zone
|
||||
elif key == 'ec2_tags':
|
||||
for k, v in value.iteritems():
|
||||
key = self.to_safe('ec2_tag_' + k)
|
||||
instance_vars[key] = v
|
||||
elif key == 'ec2_groups':
|
||||
group_ids = []
|
||||
group_names = []
|
||||
for group in value:
|
||||
group_ids.append(group.id)
|
||||
group_names.append(group.name)
|
||||
instance_vars["ec2_security_group_ids"] = ','.join([str(i) for i in group_ids])
|
||||
instance_vars["ec2_security_group_names"] = ','.join([str(i) for i in group_names])
|
||||
else:
|
||||
pass
|
||||
# TODO Product codes if someone finds them useful
|
||||
#print key
|
||||
#print type(value)
|
||||
#print value
|
||||
|
||||
return instance_vars
|
||||
|
||||
def get_host_info(self):
|
||||
''' Get variables about a specific host '''
|
||||
|
||||
if len(self.index) == 0:
|
||||
# Need to load index from cache
|
||||
self.load_index_from_cache()
|
||||
|
||||
if not self.args.host in self.index:
|
||||
# try updating the cache
|
||||
self.do_api_calls_update_cache()
|
||||
if not self.args.host in self.index:
|
||||
# host might not exist anymore
|
||||
return self.json_format_dict({}, True)
|
||||
|
||||
(region, instance_id) = self.index[self.args.host]
|
||||
|
||||
instance = self.get_instance(region, instance_id)
|
||||
return self.json_format_dict(self.get_host_info_dict_from_instance(instance), True)
|
||||
|
||||
def push(self, my_dict, key, element):
|
||||
''' Push an element onto an array that may not have been defined in
|
||||
the dict '''
|
||||
group_info = my_dict.setdefault(key, [])
|
||||
if isinstance(group_info, dict):
|
||||
host_list = group_info.setdefault('hosts', [])
|
||||
host_list.append(element)
|
||||
else:
|
||||
group_info.append(element)
|
||||
|
||||
def push_group(self, my_dict, key, element):
|
||||
''' Push a group as a child of another group. '''
|
||||
parent_group = my_dict.setdefault(key, {})
|
||||
if not isinstance(parent_group, dict):
|
||||
parent_group = my_dict[key] = {'hosts': parent_group}
|
||||
child_groups = parent_group.setdefault('children', [])
|
||||
if element not in child_groups:
|
||||
child_groups.append(element)
|
||||
|
||||
def get_inventory_from_cache(self):
|
||||
''' Reads the inventory from the cache file and returns it as a JSON
|
||||
object '''
|
||||
|
||||
cache = open(self.cache_path_cache, 'r')
|
||||
json_inventory = cache.read()
|
||||
return json_inventory
|
||||
|
||||
|
||||
def load_index_from_cache(self):
|
||||
''' Reads the index from the cache file sets self.index '''
|
||||
|
||||
cache = open(self.cache_path_index, 'r')
|
||||
json_index = cache.read()
|
||||
self.index = json.loads(json_index)
|
||||
|
||||
|
||||
def write_to_cache(self, data, filename):
|
||||
''' Writes data in JSON format to a file '''
|
||||
|
||||
json_data = self.json_format_dict(data, True)
|
||||
cache = open(filename, 'w')
|
||||
cache.write(json_data)
|
||||
cache.close()
|
||||
|
||||
|
||||
def to_safe(self, word):
|
||||
''' Converts 'bad' characters in a string to underscores so they can be
|
||||
used as Ansible groups '''
|
||||
|
||||
return re.sub("[^A-Za-z0-9\-]", "_", word)
|
||||
|
||||
|
||||
def json_format_dict(self, data, pretty=False):
|
||||
''' Converts a dict to a JSON object and dumps it as a formatted
|
||||
string '''
|
||||
|
||||
if pretty:
|
||||
return json.dumps(data, sort_keys=True, indent=2)
|
||||
else:
|
||||
return json.dumps(data)
|
||||
|
||||
|
||||
# Run the script
|
||||
Ec2Inventory()
|
||||
|
||||
|
|
@ -1,8 +1,10 @@
|
|||
---
|
||||
- name: Provision the operation system for tests
|
||||
# testing
|
||||
hosts: all
|
||||
# hosts: all
|
||||
# live
|
||||
# hosts: TDB
|
||||
hosts: tag_Name_test_runner
|
||||
remote_user: ubuntu
|
||||
roles:
|
||||
- common
|
||||
- docker
|
||||
- common
|
||||
|
|
|
|||
4
tests/files/ansible/roles/common/handlers/main.yml
Normal file
4
tests/files/ansible/roles/common/handlers/main.yml
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
---
|
||||
- name: restart sshd
|
||||
sudo: true
|
||||
service: name=ssh state=restarted
|
||||
|
|
@ -1,28 +1,13 @@
|
|||
---
|
||||
- name: install docker
|
||||
sudo: true
|
||||
# install script from https://docs.docker.com/installation/ubuntulinux/
|
||||
shell: curl -sSL https://get.docker.com/ubuntu/ | sudo sh
|
||||
|
||||
- name: install package dependencies
|
||||
sudo: true
|
||||
apt: name={{ item }}
|
||||
with_items:
|
||||
- python-pip
|
||||
- htop
|
||||
|
||||
- name: install python dependencies
|
||||
sudo: true
|
||||
pip: name=docker-py
|
||||
|
||||
|
||||
- name: enable docker for standard user
|
||||
sudo: true
|
||||
# todo: how to logout after this command, otherwise won't be effective in this play
|
||||
user: name=vagrant groups=docker append=yes
|
||||
- parallel
|
||||
- htop
|
||||
|
||||
- name: checkout test repo
|
||||
git:
|
||||
repo: https://github.com/sveneh/tests.git
|
||||
version: develop
|
||||
dest: git
|
||||
repo: https://github.com/ethereum/tests.git
|
||||
version: develop
|
||||
dest: git
|
||||
|
|
|
|||
4
tests/files/ansible/roles/docker/handlers/main.yml
Normal file
4
tests/files/ansible/roles/docker/handlers/main.yml
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
---
|
||||
- name: restart sshd
|
||||
sudo: true
|
||||
service: name=ssh state=restarted
|
||||
40
tests/files/ansible/roles/docker/tasks/main.yml
Normal file
40
tests/files/ansible/roles/docker/tasks/main.yml
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
---
|
||||
- name: update package list
|
||||
sudo: true
|
||||
apt: update_cache=true
|
||||
|
||||
- name: install docker dependencies
|
||||
sudo: true
|
||||
apt: name={{ item }} install_recommends=false
|
||||
with_items:
|
||||
# Docker has serious problems on EC2: http://www.danstutzman.com/2014/07/speed-up-docker-on-ec2
|
||||
# and https://github.com/docker/docker/issues/4036
|
||||
- linux-generic
|
||||
- python-pip
|
||||
|
||||
- name: Kernel update needs a restart
|
||||
sudo: true
|
||||
command: shutdown -r now
|
||||
async: 0
|
||||
poll: 0
|
||||
ignore_errors: true
|
||||
|
||||
- name: waiting for server to come back
|
||||
local_action: wait_for host={{ inventory_hostname }} port=22
|
||||
state=started
|
||||
sudo: false
|
||||
|
||||
- name: install docker
|
||||
sudo: true
|
||||
# install script from https://docs.docker.com/installation/ubuntulinux/
|
||||
# TODO this is not idempotent
|
||||
shell: curl -sSL https://get.docker.com/ubuntu/ | sudo sh
|
||||
|
||||
- name: install docker python API
|
||||
sudo: true
|
||||
pip: name=docker-py
|
||||
|
||||
- name: enable docker for standard user
|
||||
sudo: true
|
||||
user: name={{ ansible_ssh_user }} groups=docker append=yes
|
||||
notify: restart sshd
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue