aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--Godeps/Godeps.json4
-rw-r--r--Godeps/_workspace/src/github.com/ethereum/ethash/ethash.go48
-rw-r--r--Godeps/_workspace/src/github.com/ethereum/ethash/setup.py63
-rw-r--r--Godeps/_workspace/src/github.com/ethereum/ethash/src/benchmark/benchmark.cpp13
-rw-r--r--Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash-cl/ethash_cl_miner.cpp10
-rw-r--r--Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash-cl/ethash_cl_miner.h4
-rw-r--r--Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/ethash.h113
-rw-r--r--Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/internal.c98
-rw-r--r--Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/internal.h23
-rw-r--r--Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/io.h3
-rw-r--r--Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/sha3.h12
-rw-r--r--Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/sha3_cryptopp.cpp9
-rw-r--r--Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/sha3_cryptopp.h8
-rw-r--r--Godeps/_workspace/src/github.com/ethereum/ethash/src/python/core.c43
-rw-r--r--Godeps/_workspace/src/github.com/ethereum/ethash/test/c/test.cpp112
-rw-r--r--Godeps/_workspace/src/github.com/ethereum/ethash/test/python/test.sh13
-rw-r--r--blockpool/blockpool.go3
-rw-r--r--cmd/geth/main.go14
m---------cmd/mist/assets/ext/ethereum.js0
-rw-r--r--cmd/utils/cmd.go8
-rw-r--r--cmd/utils/flags.go7
-rw-r--r--core/block_cache_test.go2
-rw-r--r--core/chain_manager.go10
-rw-r--r--eth/backend.go14
-rw-r--r--eth/protocol_test.go4
-rw-r--r--jsre/ethereum_js.go2
-rw-r--r--jsre/pp_js.go16
-rw-r--r--logger/glog/glog.go4
-rw-r--r--logger/glog/glog_file.go4
-rw-r--r--miner/miner.go12
-rw-r--r--miner/worker.go89
-rw-r--r--p2p/discover/udp.go19
-rw-r--r--p2p/nat/nat.go13
-rw-r--r--p2p/server.go24
-rw-r--r--rpc/api.go51
-rw-r--r--rpc/args.go2
-rw-r--r--rpc/args_test.go214
-rw-r--r--rpc/responses_test.go144
-rw-r--r--rpc/types.go18
-rw-r--r--rpc/types_test.go154
-rw-r--r--whisper/whisper.go7
-rw-r--r--xeth/xeth.go28
42 files changed, 1002 insertions, 437 deletions
diff --git a/Godeps/Godeps.json b/Godeps/Godeps.json
index 3b04c5e11..c51a2312b 100644
--- a/Godeps/Godeps.json
+++ b/Godeps/Godeps.json
@@ -22,8 +22,8 @@
},
{
"ImportPath": "github.com/ethereum/ethash",
- "Comment": "v23.1-73-g67a0e12",
- "Rev": "67a0e12a091de035ef083186247e84be2d863c62"
+ "Comment": "v23.1-81-g4039fd0",
+ "Rev": "4039fd095084679fb0bf3feae91d02506b5d67aa"
},
{
"ImportPath": "github.com/ethereum/serpent-go",
diff --git a/Godeps/_workspace/src/github.com/ethereum/ethash/ethash.go b/Godeps/_workspace/src/github.com/ethereum/ethash/ethash.go
index 7291d58ba..c33bfccc4 100644
--- a/Godeps/_workspace/src/github.com/ethereum/ethash/ethash.go
+++ b/Godeps/_workspace/src/github.com/ethereum/ethash/ethash.go
@@ -34,13 +34,12 @@ import (
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/logger"
+ "github.com/ethereum/go-ethereum/logger/glog"
"github.com/ethereum/go-ethereum/pow"
)
var minDifficulty = new(big.Int).Exp(big.NewInt(2), big.NewInt(256), big.NewInt(0))
-var powlogger = logger.NewLogger("POW")
-
type ParamsAndCache struct {
params *C.ethash_params
cache *C.ethash_cache
@@ -92,10 +91,13 @@ func makeParamsAndCache(chainManager pow.ChainManager, blockNum uint64) (*Params
return nil, err
}
- powlogger.Infoln("Making Cache")
+ glog.V(logger.Info).Infoln("Making cache")
start := time.Now()
- C.ethash_mkcache(paramsAndCache.cache, paramsAndCache.params, (*C.uint8_t)(unsafe.Pointer(&seedHash[0])))
- powlogger.Infoln("Took:", time.Since(start))
+ C.ethash_mkcache(paramsAndCache.cache, paramsAndCache.params, (*C.ethash_blockhash_t)(unsafe.Pointer(&seedHash[0])))
+
+ if glog.V(logger.Info) {
+ glog.Infoln("Took:", time.Since(start))
+ }
return paramsAndCache, nil
}
@@ -131,9 +133,9 @@ func makeDAG(p *ParamsAndCache) *DAG {
for {
select {
case <-t.C:
- powlogger.Infof("... still generating DAG (%v) ...\n", time.Since(tstart).Seconds())
+ glog.V(logger.Info).Infof("... still generating DAG (%v) ...\n", time.Since(tstart).Seconds())
case str := <-donech:
- powlogger.Infof("... %s ...\n", str)
+ glog.V(logger.Info).Infof("... %s ...\n", str)
break done
}
}
@@ -193,30 +195,30 @@ func (pow *Ethash) UpdateDAG() {
pow.paramsAndCache = paramsAndCache
path := path.Join("/", "tmp", "dag")
pow.dag = nil
- powlogger.Infoln("Retrieving DAG")
+ glog.V(logger.Info).Infoln("Retrieving DAG")
start := time.Now()
file, err := os.Open(path)
if err != nil {
- powlogger.Infof("No DAG found. Generating new DAG in '%s' (this takes a while)...\n", path)
+ glog.V(logger.Info).Infof("No DAG found. Generating new DAG in '%s' (this takes a while)...\n", path)
pow.dag = makeDAG(paramsAndCache)
file = pow.writeDagToDisk(pow.dag, thisEpoch)
pow.dag.file = true
} else {
data, err := ioutil.ReadAll(file)
if err != nil {
- powlogger.Infof("DAG load err: %v\n", err)
+ glog.V(logger.Info).Infof("DAG load err: %v\n", err)
}
if len(data) < 8 {
- powlogger.Infof("DAG in '%s' is less than 8 bytes, it must be corrupted. Generating new DAG (this takes a while)...\n", path)
+ glog.V(logger.Info).Infof("DAG in '%s' is less than 8 bytes, it must be corrupted. Generating new DAG (this takes a while)...\n", path)
pow.dag = makeDAG(paramsAndCache)
file = pow.writeDagToDisk(pow.dag, thisEpoch)
pow.dag.file = true
} else {
dataEpoch := binary.BigEndian.Uint64(data[0:8])
if dataEpoch < thisEpoch {
- powlogger.Infof("DAG in '%s' is stale. Generating new DAG (this takes a while)...\n", path)
+ glog.V(logger.Info).Infof("DAG in '%s' is stale. Generating new DAG (this takes a while)...\n", path)
pow.dag = makeDAG(paramsAndCache)
file = pow.writeDagToDisk(pow.dag, thisEpoch)
pow.dag.file = true
@@ -224,7 +226,7 @@ func (pow *Ethash) UpdateDAG() {
// FIXME
panic(fmt.Errorf("Saved DAG in '%s' reports to be from future epoch %v (current epoch is %v)\n", path, dataEpoch, thisEpoch))
} else if len(data) != (int(paramsAndCache.params.full_size) + 8) {
- powlogger.Infof("DAG in '%s' is corrupted. Generating new DAG (this takes a while)...\n", path)
+ glog.V(logger.Info).Infof("DAG in '%s' is corrupted. Generating new DAG (this takes a while)...\n", path)
pow.dag = makeDAG(paramsAndCache)
file = pow.writeDagToDisk(pow.dag, thisEpoch)
pow.dag.file = true
@@ -238,7 +240,7 @@ func (pow *Ethash) UpdateDAG() {
}
}
}
- powlogger.Infoln("Took:", time.Since(start))
+ glog.V(logger.Info).Infoln("Took:", time.Since(start))
file.Close()
}
@@ -319,7 +321,7 @@ func (pow *Ethash) Search(block pow.Block, stop <-chan struct{}) (uint64, []byte
start := time.Now().UnixNano()
nonce := uint64(r.Int63())
- cMiningHash := (*C.uint8_t)(unsafe.Pointer(&miningHash[0]))
+ cMiningHash := (*C.ethash_blockhash_t)(unsafe.Pointer(&miningHash[0]))
target := new(big.Int).Div(minDifficulty, diff)
var ret C.ethash_return_value
@@ -336,11 +338,11 @@ func (pow *Ethash) Search(block pow.Block, stop <-chan struct{}) (uint64, []byte
pow.HashRate = int64(hashes)
C.ethash_full(&ret, pow.dag.dag, pow.dag.paramsAndCache.params, cMiningHash, C.uint64_t(nonce))
- result := common.Bytes2Big(C.GoBytes(unsafe.Pointer(&ret.result[0]), C.int(32)))
+ result := common.Bytes2Big(C.GoBytes(unsafe.Pointer(&ret.result), C.int(32)))
// TODO: disagrees with the spec https://github.com/ethereum/wiki/wiki/Ethash#mining
if result.Cmp(target) <= 0 {
- mixDigest := C.GoBytes(unsafe.Pointer(&ret.mix_hash[0]), C.int(32))
+ mixDigest := C.GoBytes(unsafe.Pointer(&ret.mix_hash), C.int(32))
seedHash, err := GetSeedHash(block.NumberU64()) // This seedhash is useless
if err != nil {
panic(err)
@@ -366,14 +368,14 @@ func (pow *Ethash) Verify(block pow.Block) bool {
func (pow *Ethash) verify(hash common.Hash, mixDigest common.Hash, difficulty *big.Int, blockNum uint64, nonce uint64) bool {
// Make sure the block num is valid
if blockNum >= epochLength*2048 {
- powlogger.Infoln(fmt.Sprintf("Block number exceeds limit, invalid (value is %v, limit is %v)",
+ glog.V(logger.Info).Infoln(fmt.Sprintf("Block number exceeds limit, invalid (value is %v, limit is %v)",
blockNum, epochLength*2048))
return false
}
// First check: make sure header, mixDigest, nonce are correct without hitting the cache
// This is to prevent DOS attacks
- chash := (*C.uint8_t)(unsafe.Pointer(&hash[0]))
+ chash := (*C.ethash_blockhash_t)(unsafe.Pointer(&hash[0]))
cnonce := C.uint64_t(nonce)
target := new(big.Int).Div(minDifficulty, difficulty)
@@ -387,7 +389,7 @@ func (pow *Ethash) verify(hash common.Hash, mixDigest common.Hash, difficulty *b
// If we can't make the params for some reason, this block is invalid
pAc, err = makeParamsAndCache(pow.chainManager, blockNum+1)
if err != nil {
- powlogger.Infoln("big fucking eror", err)
+ glog.V(logger.Info).Infoln("big fucking eror", err)
return false
}
} else {
@@ -401,7 +403,7 @@ func (pow *Ethash) verify(hash common.Hash, mixDigest common.Hash, difficulty *b
C.ethash_light(ret, pAc.cache, pAc.params, chash, cnonce)
- result := common.Bytes2Big(C.GoBytes(unsafe.Pointer(&ret.result[0]), C.int(32)))
+ result := common.Bytes2Big(C.GoBytes(unsafe.Pointer(&ret.result), C.int(32)))
return result.Cmp(target) <= 0
}
@@ -417,7 +419,7 @@ func (pow *Ethash) FullHash(nonce uint64, miningHash []byte) []byte {
pow.UpdateDAG()
pow.dagMutex.Lock()
defer pow.dagMutex.Unlock()
- cMiningHash := (*C.uint8_t)(unsafe.Pointer(&miningHash[0]))
+ cMiningHash := (*C.ethash_blockhash_t)(unsafe.Pointer(&miningHash[0]))
cnonce := C.uint64_t(nonce)
ret := new(C.ethash_return_value)
// pow.hash is the output/return of ethash_full
@@ -427,7 +429,7 @@ func (pow *Ethash) FullHash(nonce uint64, miningHash []byte) []byte {
}
func (pow *Ethash) LightHash(nonce uint64, miningHash []byte) []byte {
- cMiningHash := (*C.uint8_t)(unsafe.Pointer(&miningHash[0]))
+ cMiningHash := (*C.ethash_blockhash_t)(unsafe.Pointer(&miningHash[0]))
cnonce := C.uint64_t(nonce)
ret := new(C.ethash_return_value)
C.ethash_light(ret, pow.paramsAndCache.cache, pow.paramsAndCache.params, cMiningHash, cnonce)
diff --git a/Godeps/_workspace/src/github.com/ethereum/ethash/setup.py b/Godeps/_workspace/src/github.com/ethereum/ethash/setup.py
index 29d6ad6d2..6a6b93839 100644
--- a/Godeps/_workspace/src/github.com/ethereum/ethash/setup.py
+++ b/Godeps/_workspace/src/github.com/ethereum/ethash/setup.py
@@ -1,33 +1,34 @@
#!/usr/bin/env python
from distutils.core import setup, Extension
-
-pyethash = Extension('pyethash',
- sources = [
- 'src/python/core.c',
- 'src/libethash/util.c',
- 'src/libethash/internal.c',
- 'src/libethash/sha3.c'],
- depends = [
- 'src/libethash/ethash.h',
- 'src/libethash/compiler.h',
- 'src/libethash/data_sizes.h',
- 'src/libethash/endian.h',
- 'src/libethash/ethash.h',
- 'src/libethash/fnv.h',
- 'src/libethash/internal.h',
- 'src/libethash/sha3.h',
- 'src/libethash/util.h'
- ],
- extra_compile_args = ["-Isrc/", "-std=gnu99", "-Wall"])
-
-setup (
- name = 'pyethash',
- author = "Matthew Wampler-Doty",
- author_email = "matthew.wampler.doty@gmail.com",
- license = 'GPL',
- version = '23',
- url = 'https://github.com/ethereum/ethash',
- download_url = 'https://github.com/ethereum/ethash/tarball/v23',
- description = 'Python wrappers for ethash, the ethereum proof of work hashing function',
- ext_modules = [pyethash],
- )
+
+pyethash = Extension('pyethash',
+ sources=[
+ 'src/python/core.c',
+ 'src/libethash/util.c',
+ 'src/libethash/internal.c',
+ 'src/libethash/sha3.c'],
+ depends=[
+ 'src/libethash/ethash.h',
+ 'src/libethash/compiler.h',
+ 'src/libethash/data_sizes.h',
+ 'src/libethash/endian.h',
+ 'src/libethash/ethash.h',
+ 'src/libethash/fnv.h',
+ 'src/libethash/internal.h',
+ 'src/libethash/sha3.h',
+ 'src/libethash/util.h'
+ ],
+ extra_compile_args=["-Isrc/", "-std=gnu99", "-Wall"])
+
+setup(
+ name='pyethash',
+ author="Matthew Wampler-Doty",
+ author_email="matthew.wampler.doty@gmail.com",
+ license='GPL',
+ version='0.1.23',
+ url='https://github.com/ethereum/ethash',
+ download_url='https://github.com/ethereum/ethash/tarball/v23',
+ description=('Python wrappers for ethash, the ethereum proof of work'
+ 'hashing function'),
+ ext_modules=[pyethash],
+)
diff --git a/Godeps/_workspace/src/github.com/ethereum/ethash/src/benchmark/benchmark.cpp b/Godeps/_workspace/src/github.com/ethereum/ethash/src/benchmark/benchmark.cpp
index 17e9e1b7a..2635c8038 100644
--- a/Godeps/_workspace/src/github.com/ethereum/ethash/src/benchmark/benchmark.cpp
+++ b/Godeps/_workspace/src/github.com/ethereum/ethash/src/benchmark/benchmark.cpp
@@ -106,10 +106,11 @@ extern "C" int main(void)
//params.full_size = 8209 * 4096; // 8MBish;
//params.cache_size = 8209*4096;
//params.cache_size = 2053*4096;
- uint8_t seed[32], previous_hash[32];
+ ethash_blockhash_t seed;
+ ethash_blockhash_t previous_hash;
- memcpy(seed, hexStringToBytes("9410b944535a83d9adf6bbdcc80e051f30676173c16ca0d32d6f1263fc246466").data(), 32);
- memcpy(previous_hash, hexStringToBytes("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470").data(), 32);
+ memcpy(&seed, hexStringToBytes("9410b944535a83d9adf6bbdcc80e051f30676173c16ca0d32d6f1263fc246466").data(), 32);
+ memcpy(&previous_hash, hexStringToBytes("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470").data(), 32);
// allocate page aligned buffer for dataset
#ifdef FULL
@@ -128,9 +129,9 @@ extern "C" int main(void)
ethash_mkcache(&cache, &params, seed);
auto time = std::chrono::duration_cast<std::chrono::milliseconds>(high_resolution_clock::now() - startTime).count();
- uint8_t cache_hash[32];
- SHA3_256(cache_hash, (uint8_t const*)cache_mem, params.cache_size);
- debugf("ethash_mkcache: %ums, sha3: %s\n", (unsigned)time, bytesToHexString(cache_hash,sizeof(cache_hash)).data());
+ ethash_blockhash_t cache_hash;
+ SHA3_256(&cache_hash, (uint8_t const*)cache_mem, params.cache_size);
+ debugf("ethash_mkcache: %ums, sha3: %s\n", (unsigned)((time*1000)/CLOCKS_PER_SEC), bytesToHexString(cache_hash,sizeof(cache_hash)).data());
// print a couple of test hashes
{
diff --git a/Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash-cl/ethash_cl_miner.cpp b/Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash-cl/ethash_cl_miner.cpp
index e668f0622..bf7bb2128 100644
--- a/Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash-cl/ethash_cl_miner.cpp
+++ b/Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash-cl/ethash_cl_miner.cpp
@@ -54,15 +54,7 @@ ethash_cl_miner::ethash_cl_miner()
{
}
-void ethash_cl_miner::finish()
-{
- if (m_queue())
- {
- m_queue.finish();
- }
-}
-
-bool ethash_cl_miner::init(ethash_params const& params, const uint8_t seed[32], unsigned workgroup_size)
+bool ethash_cl_miner::init(ethash_params const& params, ethash_blockhash_t const *seed, unsigned workgroup_size)
{
// store params
m_params = params;
diff --git a/Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash-cl/ethash_cl_miner.h b/Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash-cl/ethash_cl_miner.h
index 7889989e3..af614b3e4 100644
--- a/Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash-cl/ethash_cl_miner.h
+++ b/Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash-cl/ethash_cl_miner.h
@@ -19,7 +19,7 @@ public:
public:
ethash_cl_miner();
- bool init(ethash_params const& params, const uint8_t seed[32], unsigned workgroup_size = 64);
+ bool init(ethash_params const& params, ethash_blockhash_t const *seed, unsigned workgroup_size = 64);
void finish();
void hash(uint8_t* ret, uint8_t const* header, uint64_t nonce, unsigned count);
@@ -42,4 +42,4 @@ private:
cl::Buffer m_search_buf[c_num_buffers];
unsigned m_workgroup_size;
bool m_opencl_1_1;
-}; \ No newline at end of file
+};
diff --git a/Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/ethash.h b/Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/ethash.h
index eb3097307..fad964449 100644
--- a/Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/ethash.h
+++ b/Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/ethash.h
@@ -47,9 +47,26 @@ typedef struct ethash_params {
uint64_t cache_size; // Size of compute cache (in bytes, multiple of node size (64)).
} ethash_params;
+/// Type of a blockhash
+typedef struct ethash_blockhash { uint8_t b[32]; } ethash_blockhash_t;
+static inline uint8_t ethash_blockhash_get(ethash_blockhash_t const* hash, unsigned int i)
+{
+ return hash->b[i];
+}
+
+static inline void ethash_blockhash_set(ethash_blockhash_t *hash, unsigned int i, uint8_t v)
+{
+ hash->b[i] = v;
+}
+
+static inline void ethash_blockhash_reset(ethash_blockhash_t *hash)
+{
+ memset(hash, 0, 32);
+}
+
typedef struct ethash_return_value {
- uint8_t result[32];
- uint8_t mix_hash[32];
+ ethash_blockhash_t result;
+ ethash_blockhash_t mix_hash;
} ethash_return_value;
uint64_t ethash_get_datasize(const uint32_t block_number);
@@ -65,58 +82,68 @@ typedef struct ethash_cache {
void *mem;
} ethash_cache;
-void ethash_mkcache(ethash_cache *cache, ethash_params const *params, const uint8_t seed[32]);
+void ethash_mkcache(ethash_cache *cache, ethash_params const *params, ethash_blockhash_t const *seed);
void ethash_compute_full_data(void *mem, ethash_params const *params, ethash_cache const *cache);
-void ethash_full(ethash_return_value *ret, void const *full_mem, ethash_params const *params, const uint8_t header_hash[32], const uint64_t nonce);
-void ethash_light(ethash_return_value *ret, ethash_cache const *cache, ethash_params const *params, const uint8_t header_hash[32], const uint64_t nonce);
-void ethash_get_seedhash(uint8_t seedhash[32], const uint32_t block_number);
-
-static inline void ethash_prep_light(void *cache, ethash_params const *params, const uint8_t seed[32]) {
- ethash_cache c;
- c.mem = cache;
- ethash_mkcache(&c, params, seed);
+void ethash_full(ethash_return_value *ret,
+ void const *full_mem,
+ ethash_params const *params,
+ ethash_blockhash_t const *header_hash,
+ const uint64_t nonce);
+void ethash_light(ethash_return_value *ret,
+ ethash_cache const *cache,
+ ethash_params const *params,
+ ethash_blockhash_t const *header_hash,
+ const uint64_t nonce);
+void ethash_get_seedhash(ethash_blockhash_t *seedhash, const uint32_t block_number);
+
+static inline void ethash_prep_light(void *cache, ethash_params const *params, ethash_blockhash_t const* seed)
+{
+ ethash_cache c;
+ c.mem = cache;
+ ethash_mkcache(&c, params, seed);
}
-static inline void ethash_compute_light(ethash_return_value *ret, void const *cache, ethash_params const *params, const uint8_t header_hash[32], const uint64_t nonce) {
- ethash_cache c;
- c.mem = (void *) cache;
- ethash_light(ret, &c, params, header_hash, nonce);
+static inline void ethash_compute_light(ethash_return_value *ret, void const *cache, ethash_params const *params, ethash_blockhash_t const *header_hash, const uint64_t nonce)
+{
+ ethash_cache c;
+ c.mem = (void *) cache;
+ ethash_light(ret, &c, params, header_hash, nonce);
}
-static inline void ethash_prep_full(void *full, ethash_params const *params, void const *cache) {
- ethash_cache c;
- c.mem = (void *) cache;
- ethash_compute_full_data(full, params, &c);
+static inline void ethash_prep_full(void *full, ethash_params const *params, void const *cache)
+{
+ ethash_cache c;
+ c.mem = (void *) cache;
+ ethash_compute_full_data(full, params, &c);
}
-static inline void ethash_compute_full(ethash_return_value *ret, void const *full, ethash_params const *params, const uint8_t header_hash[32], const uint64_t nonce) {
- ethash_full(ret, full, params, header_hash, nonce);
+static inline void ethash_compute_full(ethash_return_value *ret,
+ void const *full,
+ ethash_params const *params,
+ ethash_blockhash_t const *header_hash,
+ const uint64_t nonce)
+{
+ ethash_full(ret, full, params, header_hash, nonce);
}
-/// @brief Compare two s256-bit big-endian values.
-/// @returns 1 if @a a is less than or equal to @a b, 0 otherwise.
-/// Both parameters are 256-bit big-endian values.
-static inline int ethash_leq_be256(const uint8_t a[32], const uint8_t b[32]) {
- // Boundary is big endian
- for (int i = 0; i < 32; i++) {
- if (a[i] == b[i])
- continue;
- return a[i] < b[i];
- }
- return 1;
+// Returns if hash is less than or equal to difficulty
+static inline int ethash_check_difficulty(ethash_blockhash_t const *hash,
+ ethash_blockhash_t const *difficulty)
+{
+ // Difficulty is big endian
+ for (int i = 0; i < 32; i++) {
+ if (ethash_blockhash_get(hash, i) == ethash_blockhash_get(difficulty, i)) {
+ continue;
+ }
+ return ethash_blockhash_get(hash, i) < ethash_blockhash_get(difficulty, i);
+ }
+ return 1;
}
-/// Perofrms a cursory check on the validity of the nonce.
-/// @returns 1 if the nonce may possibly be valid for the given header_hash & boundary.
-/// @p boundary equivalent to 2 ^ 256 / block_difficulty, represented as a 256-bit big-endian.
-int ethash_preliminary_check_boundary(
- const uint8_t header_hash[32],
- const uint64_t nonce,
- const uint8_t mix_hash[32],
- const uint8_t boundary[32]);
-
-#define ethash_quick_check_difficulty ethash_preliminary_check_boundary
-#define ethash_check_difficulty ethash_leq_be256
+int ethash_quick_check_difficulty(ethash_blockhash_t const *header_hash,
+ const uint64_t nonce,
+ ethash_blockhash_t const *mix_hash,
+ ethash_blockhash_t const *difficulty);
#ifdef __cplusplus
}
diff --git a/Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/internal.c b/Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/internal.c
index ae9b95065..5009d52f5 100644
--- a/Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/internal.c
+++ b/Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/internal.c
@@ -50,14 +50,14 @@ uint64_t ethash_get_cachesize(const uint32_t block_number) {
// Follows Sergio's "STRICT MEMORY HARD HASHING FUNCTIONS" (2014)
// https://bitslog.files.wordpress.com/2013/12/memohash-v0-3.pdf
// SeqMemoHash(s, R, N)
-void static ethash_compute_cache_nodes(
- node *const nodes,
- ethash_params const *params,
- const uint8_t seed[32]) {
+void static ethash_compute_cache_nodes(node *const nodes,
+ ethash_params const *params,
+ ethash_blockhash_t const* seed)
+{
assert((params->cache_size % sizeof(node)) == 0);
uint32_t const num_nodes = (uint32_t) (params->cache_size / sizeof(node));
- SHA3_512(nodes[0].bytes, seed, 32);
+ SHA3_512(nodes[0].bytes, (uint8_t*)seed, 32);
for (unsigned i = 1; i != num_nodes; ++i) {
SHA3_512(nodes[i].bytes, nodes[i - 1].bytes, 64);
@@ -84,20 +84,19 @@ void static ethash_compute_cache_nodes(
#endif
}
-void ethash_mkcache(
- ethash_cache *cache,
- ethash_params const *params,
- const uint8_t seed[32]) {
+void ethash_mkcache(ethash_cache *cache,
+ ethash_params const *params,
+ ethash_blockhash_t const* seed)
+{
node *nodes = (node *) cache->mem;
ethash_compute_cache_nodes(nodes, params, seed);
}
-void ethash_calculate_dag_item(
- node *const ret,
- const unsigned node_index,
- const struct ethash_params *params,
- const struct ethash_cache *cache) {
-
+void ethash_calculate_dag_item(node *const ret,
+ const unsigned node_index,
+ const struct ethash_params *params,
+ const struct ethash_cache *cache)
+{
uint32_t num_parent_nodes = (uint32_t) (params->cache_size / sizeof(node));
node const *cache_nodes = (node const *) cache->mem;
node const *init = &cache_nodes[node_index % num_parent_nodes];
@@ -161,13 +160,13 @@ void ethash_compute_full_data(
}
}
-static void ethash_hash(
- ethash_return_value *ret,
- node const *full_nodes,
- ethash_cache const *cache,
- ethash_params const *params,
- const uint8_t header_hash[32],
- const uint64_t nonce) {
+static void ethash_hash(ethash_return_value *ret,
+ node const *full_nodes,
+ ethash_cache const *cache,
+ ethash_params const *params,
+ ethash_blockhash_t const *header_hash,
+ const uint64_t nonce)
+{
assert((params->full_size % MIX_WORDS) == 0);
@@ -251,16 +250,16 @@ static void ethash_hash(
}
#endif
- memcpy(ret->mix_hash, mix->bytes, 32);
+ memcpy(&ret->mix_hash, mix->bytes, 32);
// final Keccak hash
- SHA3_256(ret->result, s_mix->bytes, 64 + 32); // Keccak-256(s + compressed_mix)
+ SHA3_256(&ret->result, s_mix->bytes, 64 + 32); // Keccak-256(s + compressed_mix)
}
-void ethash_quick_hash(
- uint8_t return_hash[32],
- const uint8_t header_hash[32],
- const uint64_t nonce,
- const uint8_t mix_hash[32]) {
+void ethash_quick_hash(ethash_blockhash_t *return_hash,
+ ethash_blockhash_t const *header_hash,
+ const uint64_t nonce,
+ ethash_blockhash_t const *mix_hash)
+{
uint8_t buf[64 + 32];
memcpy(buf, header_hash, 32);
@@ -273,28 +272,39 @@ void ethash_quick_hash(
SHA3_256(return_hash, buf, 64 + 32);
}
-void ethash_get_seedhash(uint8_t seedhash[32], const uint32_t block_number) {
- memset(seedhash, 0, 32);
+void ethash_get_seedhash(ethash_blockhash_t *seedhash, const uint32_t block_number)
+{
+ ethash_blockhash_reset(seedhash);
const uint32_t epochs = block_number / EPOCH_LENGTH;
for (uint32_t i = 0; i < epochs; ++i)
- SHA3_256(seedhash, seedhash, 32);
+ SHA3_256(seedhash, (uint8_t*)seedhash, 32);
}
-int ethash_preliminary_check_boundary(
- const uint8_t header_hash[32],
- const uint64_t nonce,
- const uint8_t mix_hash[32],
- const uint8_t difficulty[32]) {
+int ethash_quick_check_difficulty(ethash_blockhash_t const *header_hash,
+ const uint64_t nonce,
+ ethash_blockhash_t const *mix_hash,
+ ethash_blockhash_t const *difficulty)
+{
- uint8_t return_hash[32];
- ethash_quick_hash(return_hash, header_hash, nonce, mix_hash);
- return ethash_leq_be256(return_hash, difficulty);
+ ethash_blockhash_t return_hash;
+ ethash_quick_hash(&return_hash, header_hash, nonce, mix_hash);
+ return ethash_check_difficulty(&return_hash, difficulty);
}
-void ethash_full(ethash_return_value *ret, void const *full_mem, ethash_params const *params, const uint8_t previous_hash[32], const uint64_t nonce) {
- ethash_hash(ret, (node const *) full_mem, NULL, params, previous_hash, nonce);
+void ethash_full(ethash_return_value *ret,
+ void const *full_mem,
+ ethash_params const *params,
+ ethash_blockhash_t const *header_hash,
+ const uint64_t nonce)
+{
+ ethash_hash(ret, (node const *) full_mem, NULL, params, header_hash, nonce);
}
-void ethash_light(ethash_return_value *ret, ethash_cache const *cache, ethash_params const *params, const uint8_t previous_hash[32], const uint64_t nonce) {
- ethash_hash(ret, NULL, cache, params, previous_hash, nonce);
+void ethash_light(ethash_return_value *ret,
+ ethash_cache const *cache,
+ ethash_params const *params,
+ ethash_blockhash_t const *header_hash,
+ const uint64_t nonce)
+{
+ ethash_hash(ret, NULL, cache, params, header_hash, nonce);
}
diff --git a/Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/internal.h b/Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/internal.h
index ddd06e8f4..1e19cd1fd 100644
--- a/Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/internal.h
+++ b/Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/internal.h
@@ -30,19 +30,16 @@ typedef union node {
} node;
-void ethash_calculate_dag_item(
- node *const ret,
- const unsigned node_index,
- ethash_params const *params,
- ethash_cache const *cache
-);
-
-void ethash_quick_hash(
- uint8_t return_hash[32],
- const uint8_t header_hash[32],
- const uint64_t nonce,
- const uint8_t mix_hash[32]);
+void ethash_calculate_dag_item(node *const ret,
+ const unsigned node_index,
+ ethash_params const *params,
+ ethash_cache const *cache);
+
+void ethash_quick_hash(ethash_blockhash_t *return_hash,
+ ethash_blockhash_t const *header_hash,
+ const uint64_t nonce,
+ ethash_blockhash_t const *mix_hash);
#ifdef __cplusplus
}
-#endif \ No newline at end of file
+#endif
diff --git a/Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/io.h b/Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/io.h
index dd611754d..8cf8b69bf 100644
--- a/Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/io.h
+++ b/Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/io.h
@@ -28,8 +28,6 @@
extern "C" {
#endif
-typedef struct ethash_blockhash { uint8_t b[32]; } ethash_blockhash_t;
-
static const char DAG_FILE_NAME[] = "full";
static const char DAG_MEMO_NAME[] = "full.info";
// MSVC thinks that "static const unsigned int" is not a compile time variable. Sorry for the #define :(
@@ -54,6 +52,7 @@ enum ethash_io_rc {
* @return For possible return values @see enum ethash_io_rc
*/
enum ethash_io_rc ethash_io_prepare(char const *dirname, ethash_blockhash_t seedhash);
+
/**
* Fully computes data and writes it to the file on disk.
*
diff --git a/Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/sha3.h b/Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/sha3.h
index 36a0a5301..84dca241b 100644
--- a/Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/sha3.h
+++ b/Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/sha3.h
@@ -8,20 +8,24 @@ extern "C" {
#include <stdint.h>
#include <stdlib.h>
+struct ethash_blockhash;
+
#define decsha3(bits) \
int sha3_##bits(uint8_t*, size_t, const uint8_t*, size_t);
decsha3(256)
decsha3(512)
-static inline void SHA3_256(uint8_t * const ret, uint8_t const *data, const size_t size) {
- sha3_256(ret, 32, data, size);
+static inline void SHA3_256(struct ethash_blockhash const* ret, uint8_t const *data, const size_t size)
+{
+ sha3_256((uint8_t*)ret, 32, data, size);
}
-static inline void SHA3_512(uint8_t * const ret, uint8_t const *data, const size_t size) {
+static inline void SHA3_512(uint8_t *ret, uint8_t const *data, const size_t size)
+{
sha3_512(ret, 64, data, size);
}
#ifdef __cplusplus
}
-#endif \ No newline at end of file
+#endif
diff --git a/Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/sha3_cryptopp.cpp b/Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/sha3_cryptopp.cpp
index 6cbbcad8f..e4d8b1855 100644
--- a/Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/sha3_cryptopp.cpp
+++ b/Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/sha3_cryptopp.cpp
@@ -19,16 +19,17 @@
* @author Tim Hughes <tim@twistedfury.com>
* @date 2015
*/
-
#include <stdint.h>
#include <cryptopp/sha3.h>
extern "C" {
-void SHA3_256(uint8_t *const ret, const uint8_t *data, size_t size) {
- CryptoPP::SHA3_256().CalculateDigest(ret, data, size);
+struct ethash_blockhash;
+typedef struct ethash_blockhash ethash_blockhash_t;
+void SHA3_256(ethash_blockhash_t const* ret, const uint8_t *data, size_t size) {
+ CryptoPP::SHA3_256().CalculateDigest((uint8_t*)ret, data, size);
}
void SHA3_512(uint8_t *const ret, const uint8_t *data, size_t size) {
CryptoPP::SHA3_512().CalculateDigest(ret, data, size);
}
-} \ No newline at end of file
+}
diff --git a/Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/sha3_cryptopp.h b/Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/sha3_cryptopp.h
index f910960e1..6b257b87c 100644
--- a/Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/sha3_cryptopp.h
+++ b/Godeps/_workspace/src/github.com/ethereum/ethash/src/libethash/sha3_cryptopp.h
@@ -2,14 +2,18 @@
#include "compiler.h"
#include <stdint.h>
+#include <stdlib.h>
#ifdef __cplusplus
extern "C" {
#endif
-void SHA3_256(uint8_t *const ret, const uint8_t *data, size_t size);
+struct ethash_blockhash;
+typedef struct ethash_blockhash ethash_blockhash_t;
+
+void SHA3_256(ethash_blockhash_t *const ret, const uint8_t *data, size_t size);
void SHA3_512(uint8_t *const ret, const uint8_t *data, size_t size);
#ifdef __cplusplus
}
-#endif \ No newline at end of file
+#endif
diff --git a/Godeps/_workspace/src/github.com/ethereum/ethash/src/python/core.c b/Godeps/_workspace/src/github.com/ethereum/ethash/src/python/core.c
index 1ad973a87..9024bd584 100644
--- a/Godeps/_workspace/src/github.com/ethereum/ethash/src/python/core.c
+++ b/Godeps/_workspace/src/github.com/ethereum/ethash/src/python/core.c
@@ -69,7 +69,7 @@ mkcache_bytes(PyObject *self, PyObject *args) {
params.cache_size = (size_t) cache_size;
ethash_cache cache;
cache.mem = malloc(cache_size);
- ethash_mkcache(&cache, &params, (uint8_t *) seed);
+ ethash_mkcache(&cache, &params, (ethash_blockhash_t *) seed);
PyObject * val = Py_BuildValue(PY_STRING_FORMAT, cache.mem, cache_size);
free(cache.mem);
return val;
@@ -114,28 +114,25 @@ calc_dataset_bytes(PyObject *self, PyObject *args) {
// hashimoto_light(full_size, cache, header, nonce)
static PyObject *
hashimoto_light(PyObject *self, PyObject *args) {
- char *cache_bytes, *header;
+ char *cache_bytes;
+ char *header;
unsigned long full_size;
unsigned long long nonce;
int cache_size, header_size;
-
if (!PyArg_ParseTuple(args, "k" PY_STRING_FORMAT PY_STRING_FORMAT "K", &full_size, &cache_bytes, &cache_size, &header, &header_size, &nonce))
return 0;
-
if (full_size % MIX_WORDS != 0) {
char error_message[1024];
sprintf(error_message, "The size of data set must be a multiple of %i bytes (was %lu)", MIX_WORDS, full_size);
PyErr_SetString(PyExc_ValueError, error_message);
return 0;
}
-
if (cache_size % HASH_BYTES != 0) {
char error_message[1024];
sprintf(error_message, "The size of the cache must be a multiple of %i bytes (was %i)", HASH_BYTES, cache_size);
PyErr_SetString(PyExc_ValueError, error_message);
return 0;
}
-
if (header_size != 32) {
char error_message[1024];
sprintf(error_message, "Seed must be 32 bytes long (was %i)", header_size);
@@ -143,23 +140,23 @@ hashimoto_light(PyObject *self, PyObject *args) {
return 0;
}
-
ethash_return_value out;
ethash_params params;
params.cache_size = (size_t) cache_size;
params.full_size = (size_t) full_size;
ethash_cache cache;
cache.mem = (void *) cache_bytes;
- ethash_light(&out, &cache, &params, (uint8_t *) header, nonce);
+ ethash_light(&out, &cache, &params, (ethash_blockhash_t *) header, nonce);
return Py_BuildValue("{" PY_CONST_STRING_FORMAT ":" PY_STRING_FORMAT "," PY_CONST_STRING_FORMAT ":" PY_STRING_FORMAT "}",
- "mix digest", out.mix_hash, 32,
- "result", out.result, 32);
+ "mix digest", &out.mix_hash, 32,
+ "result", &out.result, 32);
}
// hashimoto_full(dataset, header, nonce)
static PyObject *
hashimoto_full(PyObject *self, PyObject *args) {
- char *full_bytes, *header;
+ char *full_bytes;
+ char *header;
unsigned long long nonce;
int full_size, header_size;
@@ -184,16 +181,18 @@ hashimoto_full(PyObject *self, PyObject *args) {
ethash_return_value out;
ethash_params params;
params.full_size = (size_t) full_size;
- ethash_full(&out, (void *) full_bytes, &params, (uint8_t *) header, nonce);
+ ethash_full(&out, (void *) full_bytes, &params, (ethash_blockhash_t *) header, nonce);
return Py_BuildValue("{" PY_CONST_STRING_FORMAT ":" PY_STRING_FORMAT ", " PY_CONST_STRING_FORMAT ":" PY_STRING_FORMAT "}",
- "mix digest", out.mix_hash, 32,
- "result", out.result, 32);
+ "mix digest", &out.mix_hash, 32,
+ "result", &out.result, 32);
}
// mine(dataset_bytes, header, difficulty_bytes)
static PyObject *
mine(PyObject *self, PyObject *args) {
- char *full_bytes, *header, *difficulty;
+ char *full_bytes;
+ char *header;
+ char *difficulty;
srand(time(0));
uint64_t nonce = ((uint64_t) rand()) << 32 | rand();
int full_size, header_size, difficulty_size;
@@ -228,13 +227,13 @@ mine(PyObject *self, PyObject *args) {
// TODO: Multi threading?
do {
- ethash_full(&out, (void *) full_bytes, &params, (const uint8_t *) header, nonce++);
+ ethash_full(&out, (void *) full_bytes, &params, (const ethash_blockhash_t *) header, nonce++);
// TODO: disagrees with the spec https://github.com/ethereum/wiki/wiki/Ethash#mining
- } while (!ethash_check_difficulty(out.result, (const uint8_t *) difficulty));
+ } while (!ethash_check_difficulty(&out.result, (const ethash_blockhash_t *) difficulty));
return Py_BuildValue("{" PY_CONST_STRING_FORMAT ":" PY_STRING_FORMAT ", " PY_CONST_STRING_FORMAT ":" PY_STRING_FORMAT ", " PY_CONST_STRING_FORMAT ":K}",
- "mix digest", out.mix_hash, 32,
- "result", out.result, 32,
+ "mix digest", &out.mix_hash, 32,
+ "result", &out.result, 32,
"nonce", nonce);
}
@@ -251,9 +250,9 @@ get_seedhash(PyObject *self, PyObject *args) {
PyErr_SetString(PyExc_ValueError, error_message);
return 0;
}
- uint8_t seedhash[32];
- ethash_get_seedhash(seedhash, block_number);
- return Py_BuildValue(PY_STRING_FORMAT, (char *) seedhash, 32);
+ ethash_blockhash_t seedhash;
+ ethash_get_seedhash(&seedhash, block_number);
+ return Py_BuildValue(PY_STRING_FORMAT, (char *) &seedhash, 32);
}
static PyMethodDef PyethashMethods[] =
diff --git a/Godeps/_workspace/src/github.com/ethereum/ethash/test/c/test.cpp b/Godeps/_workspace/src/github.com/ethereum/ethash/test/c/test.cpp
index 904f4f74c..ffe8d53f3 100644
--- a/Godeps/_workspace/src/github.com/ethereum/ethash/test/c/test.cpp
+++ b/Godeps/_workspace/src/github.com/ethereum/ethash/test/c/test.cpp
@@ -37,6 +37,10 @@ std::string bytesToHexString(const uint8_t *str, const uint64_t s) {
return ret.str();
}
+std::string blockhashToHexString(ethash_blockhash_t *hash) {
+ return bytesToHexString((uint8_t*)hash, 32);
+}
+
BOOST_AUTO_TEST_CASE(fnv_hash_check) {
uint32_t x = 1235U;
const uint32_t
@@ -52,12 +56,13 @@ BOOST_AUTO_TEST_CASE(fnv_hash_check) {
}
BOOST_AUTO_TEST_CASE(SHA256_check) {
- uint8_t input[32], out[32];
- memcpy(input, "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", 32);
- SHA3_256(out, input, 32);
+ ethash_blockhash_t input;
+ ethash_blockhash_t out;
+ memcpy(&input, "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", 32);
+ SHA3_256(&out, (uint8_t*)&input, 32);
const std::string
expected = "2b5ddf6f4d21c23de216f44d5e4bdc68e044b71897837ea74c83908be7037cd7",
- actual = bytesToHexString(out, 32);
+ actual = bytesToHexString((uint8_t*)&out, 32);
BOOST_REQUIRE_MESSAGE(expected == actual,
"\nexpected: " << expected.c_str() << "\n"
<< "actual: " << actual.c_str() << "\n");
@@ -104,23 +109,26 @@ BOOST_AUTO_TEST_CASE(ethash_params_init_genesis_calcifide_check) {
BOOST_AUTO_TEST_CASE(light_and_full_client_checks) {
ethash_params params;
- uint8_t seed[32], hash[32], difficulty[32];
- ethash_return_value light_out, full_out;
- memcpy(seed, "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", 32);
- memcpy(hash, "~~~X~~~~~~~~~~~~~~~~~~~~~~~~~~~~", 32);
+ ethash_blockhash_t seed;
+ ethash_blockhash_t hash;
+ ethash_blockhash_t difficulty;
+ ethash_return_value light_out;
+ ethash_return_value full_out;
+ memcpy(&seed, "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", 32);
+ memcpy(&hash, "~~~X~~~~~~~~~~~~~~~~~~~~~~~~~~~~", 32);
// Set the difficulty
- difficulty[0] = 197;
- difficulty[1] = 90;
+ ethash_blockhash_set(&difficulty, 0, 197);
+ ethash_blockhash_set(&difficulty, 1, 90);
for (int i = 2; i < 32; i++)
- difficulty[i] = (uint8_t) 255;
+ ethash_blockhash_set(&difficulty, i, 255);
ethash_params_init(&params, 0);
params.cache_size = 1024;
params.full_size = 1024 * 32;
ethash_cache cache;
cache.mem = our_alloca(params.cache_size);
- ethash_mkcache(&cache, &params, seed);
+ ethash_mkcache(&cache, &params, &seed);
node *full_mem = (node *) our_alloca(params.full_size);
ethash_compute_full_data(full_mem, &params, &cache);
@@ -164,78 +172,76 @@ BOOST_AUTO_TEST_CASE(light_and_full_client_checks) {
{
uint64_t nonce = 0x7c7c597c;
- ethash_full(&full_out, full_mem, &params, hash, nonce);
- ethash_light(&light_out, &cache, &params, hash, nonce);
+ ethash_full(&full_out, full_mem, &params, &hash, nonce);
+ ethash_light(&light_out, &cache, &params, &hash, nonce);
const std::string
- light_result_string = bytesToHexString(light_out.result, 32),
- full_result_string = bytesToHexString(full_out.result, 32);
+ light_result_string = blockhashToHexString(&light_out.result),
+ full_result_string = blockhashToHexString(&full_out.result);
BOOST_REQUIRE_MESSAGE(light_result_string == full_result_string,
"\nlight result: " << light_result_string.c_str() << "\n"
<< "full result: " << full_result_string.c_str() << "\n");
const std::string
- light_mix_hash_string = bytesToHexString(light_out.mix_hash, 32),
- full_mix_hash_string = bytesToHexString(full_out.mix_hash, 32);
+ light_mix_hash_string = blockhashToHexString(&light_out.mix_hash),
+ full_mix_hash_string = blockhashToHexString(&full_out.mix_hash);
BOOST_REQUIRE_MESSAGE(full_mix_hash_string == light_mix_hash_string,
"\nlight mix hash: " << light_mix_hash_string.c_str() << "\n"
<< "full mix hash: " << full_mix_hash_string.c_str() << "\n");
- uint8_t check_hash[32];
- ethash_quick_hash(check_hash, hash, nonce, full_out.mix_hash);
- const std::string check_hash_string = bytesToHexString(check_hash, 32);
+ ethash_blockhash_t check_hash;
+ ethash_quick_hash(&check_hash, &hash, nonce, &full_out.mix_hash);
+ const std::string check_hash_string = blockhashToHexString(&check_hash);
BOOST_REQUIRE_MESSAGE(check_hash_string == full_result_string,
"\ncheck hash string: " << check_hash_string.c_str() << "\n"
<< "full result: " << full_result_string.c_str() << "\n");
}
{
- ethash_full(&full_out, full_mem, &params, hash, 5);
+ ethash_full(&full_out, full_mem, &params, &hash, 5);
std::string
- light_result_string = bytesToHexString(light_out.result, 32),
- full_result_string = bytesToHexString(full_out.result, 32);
+ light_result_string = blockhashToHexString(&light_out.result),
+ full_result_string = blockhashToHexString(&full_out.result);
BOOST_REQUIRE_MESSAGE(light_result_string != full_result_string,
"\nlight result and full result should differ: " << light_result_string.c_str() << "\n");
- ethash_light(&light_out, &cache, &params, hash, 5);
- light_result_string = bytesToHexString(light_out.result, 32);
+ ethash_light(&light_out, &cache, &params, &hash, 5);
+ light_result_string = blockhashToHexString(&light_out.result);
BOOST_REQUIRE_MESSAGE(light_result_string == full_result_string,
"\nlight result and full result should be the same\n"
<< "light result: " << light_result_string.c_str() << "\n"
<< "full result: " << full_result_string.c_str() << "\n");
std::string
- light_mix_hash_string = bytesToHexString(light_out.mix_hash, 32),
- full_mix_hash_string = bytesToHexString(full_out.mix_hash, 32);
+ light_mix_hash_string = blockhashToHexString(&light_out.mix_hash),
+ full_mix_hash_string = blockhashToHexString(&full_out.mix_hash);
BOOST_REQUIRE_MESSAGE(full_mix_hash_string == light_mix_hash_string,
"\nlight mix hash: " << light_mix_hash_string.c_str() << "\n"
<< "full mix hash: " << full_mix_hash_string.c_str() << "\n");
- BOOST_REQUIRE_MESSAGE(ethash_check_difficulty(full_out.result, difficulty),
+ BOOST_REQUIRE_MESSAGE(ethash_check_difficulty(&full_out.result, &difficulty),
"ethash_check_difficulty failed"
);
- BOOST_REQUIRE_MESSAGE(ethash_quick_check_difficulty(hash, 5U, full_out.mix_hash, difficulty),
+ BOOST_REQUIRE_MESSAGE(ethash_quick_check_difficulty(&hash, 5U, &full_out.mix_hash, &difficulty),
"ethash_quick_check_difficulty failed"
);
}
}
BOOST_AUTO_TEST_CASE(ethash_check_difficulty_check) {
- uint8_t hash[32], target[32];
- memset(hash, 0, 32);
- memset(target, 0, 32);
-
- memcpy(hash, "11111111111111111111111111111111", 32);
- memcpy(target, "22222222222222222222222222222222", 32);
+ ethash_blockhash_t hash;
+ ethash_blockhash_t target;
+ memcpy(&hash, "11111111111111111111111111111111", 32);
+ memcpy(&target, "22222222222222222222222222222222", 32);
BOOST_REQUIRE_MESSAGE(
- ethash_check_difficulty(hash, target),
- "\nexpected \"" << std::string((char *) hash, 32).c_str() << "\" to have the same or less difficulty than \"" << std::string((char *) target, 32).c_str() << "\"\n");
+ ethash_check_difficulty(&hash, &target),
+ "\nexpected \"" << std::string((char *) &hash, 32).c_str() << "\" to have the same or less difficulty than \"" << std::string((char *) &target, 32).c_str() << "\"\n");
BOOST_REQUIRE_MESSAGE(
- ethash_check_difficulty(hash, hash),
- "\nexpected \"" << hash << "\" to have the same or less difficulty than \"" << hash << "\"\n");
- memcpy(target, "11111111111111111111111111111112", 32);
+ ethash_check_difficulty(&hash, &hash), "");
+ // "\nexpected \"" << hash << "\" to have the same or less difficulty than \"" << hash << "\"\n");
+ memcpy(&target, "11111111111111111111111111111112", 32);
BOOST_REQUIRE_MESSAGE(
- ethash_check_difficulty(hash, target),
- "\nexpected \"" << hash << "\" to have the same or less difficulty than \"" << target << "\"\n");
- memcpy(target, "11111111111111111111111111111110", 32);
+ ethash_check_difficulty(&hash, &target), "");
+ // "\nexpected \"" << hash << "\" to have the same or less difficulty than \"" << target << "\"\n");
+ memcpy(&target, "11111111111111111111111111111110", 32);
BOOST_REQUIRE_MESSAGE(
- !ethash_check_difficulty(hash, target),
- "\nexpected \"" << hash << "\" to have more difficulty than \"" << target << "\"\n");
+ !ethash_check_difficulty(&hash, &target), "");
+ // "\nexpected \"" << hash << "\" to have more difficulty than \"" << target << "\"\n");
}
BOOST_AUTO_TEST_CASE(test_ethash_dir_creation) {
@@ -256,7 +262,7 @@ BOOST_AUTO_TEST_CASE(test_ethash_dir_creation) {
BOOST_AUTO_TEST_CASE(test_ethash_io_write_files_are_created) {
ethash_blockhash_t seedhash;
static const int blockn = 0;
- ethash_get_seedhash((uint8_t*)&seedhash, blockn);
+ ethash_get_seedhash(&seedhash, blockn);
BOOST_REQUIRE_EQUAL(
ETHASH_IO_MEMO_MISMATCH,
ethash_io_prepare("./test_ethash_directory/", seedhash)
@@ -273,7 +279,7 @@ BOOST_AUTO_TEST_CASE(test_ethash_io_write_files_are_created) {
params.cache_size = 1024;
params.full_size = 1024 * 32;
cache.mem = our_alloca(params.cache_size);
- ethash_mkcache(&cache, &params, (uint8_t*)&seedhash);
+ ethash_mkcache(&cache, &params, &seedhash);
BOOST_REQUIRE(
ethash_io_write("./test_ethash_directory/", &params, seedhash, &cache, &data, &size)
@@ -290,7 +296,7 @@ BOOST_AUTO_TEST_CASE(test_ethash_io_write_files_are_created) {
BOOST_AUTO_TEST_CASE(test_ethash_io_memo_file_match) {
ethash_blockhash_t seedhash;
static const int blockn = 0;
- ethash_get_seedhash((uint8_t*)&seedhash, blockn);
+ ethash_get_seedhash(&seedhash, blockn);
BOOST_REQUIRE_EQUAL(
ETHASH_IO_MEMO_MISMATCH,
ethash_io_prepare("./test_ethash_directory/", seedhash)
@@ -307,7 +313,7 @@ BOOST_AUTO_TEST_CASE(test_ethash_io_memo_file_match) {
params.cache_size = 1024;
params.full_size = 1024 * 32;
cache.mem = our_alloca(params.cache_size);
- ethash_mkcache(&cache, &params, (uint8_t*)&seedhash);
+ ethash_mkcache(&cache, &params, &seedhash);
BOOST_REQUIRE(
ethash_io_write("./test_ethash_directory/", &params, seedhash, &cache, &data, &size)
@@ -344,7 +350,7 @@ static std::vector<char> readFileIntoVector(char const* filename)
BOOST_AUTO_TEST_CASE(test_ethash_io_memo_file_contents) {
ethash_blockhash_t seedhash;
static const int blockn = 0;
- ethash_get_seedhash((uint8_t*)&seedhash, blockn);
+ ethash_get_seedhash(&seedhash, blockn);
BOOST_REQUIRE_EQUAL(
ETHASH_IO_MEMO_MISMATCH,
ethash_io_prepare("./test_ethash_directory/", seedhash)
@@ -361,8 +367,8 @@ BOOST_AUTO_TEST_CASE(test_ethash_io_memo_file_contents) {
params.cache_size = 1024;
params.full_size = 1024 * 32;
cache.mem = our_alloca(params.cache_size);
- ethash_mkcache(&cache, &params, (uint8_t*)&seedhash);
-
+ ethash_mkcache(&cache, &params, &seedhash);
+
BOOST_REQUIRE(
ethash_io_write("./test_ethash_directory/", &params, seedhash, &cache, &data, &size)
);
diff --git a/Godeps/_workspace/src/github.com/ethereum/ethash/test/python/test.sh b/Godeps/_workspace/src/github.com/ethereum/ethash/test/python/test.sh
index 95cea0215..05c66b550 100644
--- a/Godeps/_workspace/src/github.com/ethereum/ethash/test/python/test.sh
+++ b/Godeps/_workspace/src/github.com/ethereum/ethash/test/python/test.sh
@@ -3,6 +3,15 @@
# Strict mode
set -e
+if [ -x "$(which virtualenv2)" ] ; then
+ VIRTUALENV_EXEC=virtualenv2
+elif [ -x "$(which virtualenv)" ] ; then
+ VIRTUALENV_EXEC=virtualenv
+else
+ echo "Could not find a suitable version of virtualenv"
+ false
+fi
+
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do
DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
@@ -11,9 +20,11 @@ while [ -h "$SOURCE" ]; do
done
TEST_DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
-[ -d $TEST_DIR/python-virtual-env ] || virtualenv --system-site-packages $TEST_DIR/python-virtual-env
+[ -d $TEST_DIR/python-virtual-env ] || $VIRTUALENV_EXEC --system-site-packages $TEST_DIR/python-virtual-env
source $TEST_DIR/python-virtual-env/bin/activate
pip install -r $TEST_DIR/requirements.txt > /dev/null
+# force installation of nose in virtualenv even if existing in thereuser's system
+pip install nose -I
pip install --upgrade --no-deps --force-reinstall -e $TEST_DIR/../..
cd $TEST_DIR
nosetests --with-doctest -v --nocapture
diff --git a/blockpool/blockpool.go b/blockpool/blockpool.go
index 00dad3330..3b3de928d 100644
--- a/blockpool/blockpool.go
+++ b/blockpool/blockpool.go
@@ -12,6 +12,7 @@ import (
"github.com/ethereum/go-ethereum/errs"
"github.com/ethereum/go-ethereum/event"
ethlogger "github.com/ethereum/go-ethereum/logger"
+ "github.com/ethereum/go-ethereum/logger/glog"
"github.com/ethereum/go-ethereum/pow"
)
@@ -260,7 +261,7 @@ func (self *BlockPool) Start() {
}
}
}()
- plog.Infoln("Started")
+ glog.V(ethlogger.Info).Infoln("Blockpool started")
}
func (self *BlockPool) Stop() {
diff --git a/cmd/geth/main.go b/cmd/geth/main.go
index a3fe84bb8..9437f8eb4 100644
--- a/cmd/geth/main.go
+++ b/cmd/geth/main.go
@@ -46,10 +46,7 @@ const (
Version = "0.9.7"
)
-var (
- clilogger = logger.NewLogger("CLI")
- app = utils.NewApp(Version, "the go-ethereum command line interface")
-)
+var app = utils.NewApp(Version, "the go-ethereum command line interface")
func init() {
app.Action = run
@@ -217,9 +214,6 @@ JavaScript API. See https://github.com/ethereum/go-ethereum/wiki/Javascipt-Conso
utils.DataDirFlag,
utils.JSpathFlag,
utils.ListenPortFlag,
- utils.LogFileFlag,
- utils.LogJSONFlag,
- utils.LogLevelFlag,
utils.MaxPeersFlag,
utils.EtherbaseFlag,
utils.MinerThreadsFlag,
@@ -234,8 +228,12 @@ JavaScript API. See https://github.com/ethereum/go-ethereum/wiki/Javascipt-Conso
utils.ProtocolVersionFlag,
utils.NetworkIdFlag,
utils.RPCCORSDomainFlag,
+ utils.LogLevelFlag,
utils.BacktraceAtFlag,
utils.LogToStdErrFlag,
+ utils.LogVModuleFlag,
+ utils.LogFileFlag,
+ utils.LogJSONFlag,
}
// missing:
@@ -250,6 +248,7 @@ JavaScript API. See https://github.com/ethereum/go-ethereum/wiki/Javascipt-Conso
}
func main() {
+ fmt.Printf("Welcome to the FRONTIER\n")
runtime.GOMAXPROCS(runtime.NumCPU())
defer logger.Flush()
if err := app.Run(os.Args); err != nil {
@@ -259,7 +258,6 @@ func main() {
}
func run(ctx *cli.Context) {
- fmt.Printf("Welcome to the FRONTIER\n")
utils.HandleInterrupt()
cfg := utils.MakeEthConfig(ClientIdentifier, Version, ctx)
ethereum, err := eth.New(cfg)
diff --git a/cmd/mist/assets/ext/ethereum.js b/cmd/mist/assets/ext/ethereum.js
-Subproject 31e046dbecea51d3b99b21f3e7e60ddfb6c3930
+Subproject c80ede50c3b60a482f1ec76038325ec52f5e73b
diff --git a/cmd/utils/cmd.go b/cmd/utils/cmd.go
index feea29d64..a6140d233 100644
--- a/cmd/utils/cmd.go
+++ b/cmd/utils/cmd.go
@@ -33,10 +33,10 @@ import (
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/eth"
"github.com/ethereum/go-ethereum/logger"
+ "github.com/ethereum/go-ethereum/logger/glog"
"github.com/ethereum/go-ethereum/rlp"
)
-var clilogger = logger.NewLogger("CLI")
var interruptCallbacks = []func(os.Signal){}
// Register interrupt handlers callbacks
@@ -50,7 +50,7 @@ func HandleInterrupt() {
go func() {
signal.Notify(c, os.Interrupt)
for sig := range c {
- clilogger.Errorf("Shutting down (%v) ... \n", sig)
+ glog.V(logger.Error).Infof("Shutting down (%v) ... \n", sig)
RunInterruptCallbacks(sig)
}
}()
@@ -113,7 +113,7 @@ func Fatalf(format string, args ...interface{}) {
}
func StartEthereum(ethereum *eth.Ethereum) {
- clilogger.Infoln("Starting ", ethereum.Name())
+ glog.V(logger.Info).Infoln("Starting ", ethereum.Name())
if err := ethereum.Start(); err != nil {
exit(err)
}
@@ -124,7 +124,7 @@ func StartEthereum(ethereum *eth.Ethereum) {
}
func StartEthereumForTest(ethereum *eth.Ethereum) {
- clilogger.Infoln("Starting ", ethereum.Name())
+ glog.V(logger.Info).Infoln("Starting ", ethereum.Name())
ethereum.StartForTest()
RegisterInterrupt(func(sig os.Signal) {
ethereum.Stop()
diff --git a/cmd/utils/flags.go b/cmd/utils/flags.go
index 0609bcf75..51844a68e 100644
--- a/cmd/utils/flags.go
+++ b/cmd/utils/flags.go
@@ -194,6 +194,11 @@ var (
Name: "logtostderr",
Usage: "Logs are written to standard error instead of to files.",
}
+ LogVModuleFlag = cli.GenericFlag{
+ Name: "vmodule",
+ Usage: "The syntax of the argument is a comma-separated list of pattern=N, where pattern is a literal file name (minus the \".go\" suffix) or \"glob\" pattern and N is a V level.",
+ Value: glog.GetVModule(),
+ }
)
func GetNAT(ctx *cli.Context) nat.Interface {
@@ -227,6 +232,8 @@ func MakeEthConfig(clientID, version string, ctx *cli.Context) *eth.Config {
glog.SetV(ctx.GlobalInt(LogLevelFlag.Name))
// Set the log type
glog.SetToStderr(ctx.GlobalBool(LogToStdErrFlag.Name))
+ // Set the log dir
+ glog.SetLogDir(ctx.GlobalString(LogFileFlag.Name))
return &eth.Config{
Name: common.MakeName(clientID, version),
diff --git a/core/block_cache_test.go b/core/block_cache_test.go
index 434b97792..43ab847f9 100644
--- a/core/block_cache_test.go
+++ b/core/block_cache_test.go
@@ -11,7 +11,7 @@ import (
func newChain(size int) (chain []*types.Block) {
var parentHash common.Hash
for i := 0; i < size; i++ {
- block := types.NewBlock(parentHash, common.Address{}, common.Hash{}, new(big.Int), 0, "")
+ block := types.NewBlock(parentHash, common.Address{}, common.Hash{}, new(big.Int), 0, nil)
block.Header().Number = big.NewInt(int64(i))
chain = append(chain, block)
parentHash = block.Hash()
diff --git a/core/chain_manager.go b/core/chain_manager.go
index c2e241e90..3ab95d272 100644
--- a/core/chain_manager.go
+++ b/core/chain_manager.go
@@ -452,7 +452,7 @@ func (self *ChainManager) InsertChain(chain types.Blocks) error {
var (
queue = make([]interface{}, len(chain))
queueEvent = queueEvent{queue: queue}
- stats struct{ delayed, processed int }
+ stats struct{ queued, processed int }
tstart = time.Now()
)
for i, block := range chain {
@@ -472,13 +472,13 @@ func (self *ChainManager) InsertChain(chain types.Blocks) error {
// future block for future use
if err == BlockFutureErr {
self.futureBlocks.Push(block)
- stats.delayed++
+ stats.queued++
continue
}
if IsParentErr(err) && self.futureBlocks.Has(block.ParentHash()) {
self.futureBlocks.Push(block)
- stats.delayed++
+ stats.queued++
continue
}
@@ -545,10 +545,10 @@ func (self *ChainManager) InsertChain(chain types.Blocks) error {
}
- if (stats.delayed > 0 || stats.processed > 0) && bool(glog.V(logger.Info)) {
+ if (stats.queued > 0 || stats.processed > 0) && bool(glog.V(logger.Info)) {
tend := time.Since(tstart)
start, end := chain[0], chain[len(chain)-1]
- glog.Infof("imported %d block(s) %d delayed in %v. #%v [%x / %x]\n", stats.processed, stats.delayed, tend, end.Number(), start.Hash().Bytes()[:4], end.Hash().Bytes()[:4])
+ glog.Infof("imported %d block(s) %d queued in %v. #%v [%x / %x]\n", stats.processed, stats.queued, tend, end.Number(), start.Hash().Bytes()[:4], end.Hash().Bytes()[:4])
}
go self.eventMux.Post(queueEvent)
diff --git a/eth/backend.go b/eth/backend.go
index ffc970212..6b60af1f1 100644
--- a/eth/backend.go
+++ b/eth/backend.go
@@ -18,6 +18,7 @@ import (
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/logger"
+ "github.com/ethereum/go-ethereum/logger/glog"
"github.com/ethereum/go-ethereum/miner"
"github.com/ethereum/go-ethereum/p2p"
"github.com/ethereum/go-ethereum/p2p/discover"
@@ -26,7 +27,6 @@ import (
)
var (
- servlogger = logger.NewLogger("SERV")
jsonlogger = logger.NewJsonLogger()
defaultBootNodes = []*discover.Node{
@@ -83,7 +83,7 @@ func (cfg *Config) parseBootNodes() []*discover.Node {
}
n, err := discover.ParseNode(url)
if err != nil {
- servlogger.Errorf("Bootstrap URL %s: %v\n", url, err)
+ glog.V(logger.Error).Infof("Bootstrap URL %s: %v\n", url, err)
continue
}
ns = append(ns, n)
@@ -107,7 +107,7 @@ func (cfg *Config) nodeKey() (*ecdsa.PrivateKey, error) {
return nil, fmt.Errorf("could not generate server key: %v", err)
}
if err := ioutil.WriteFile(keyfile, crypto.FromECDSA(key), 0600); err != nil {
- servlogger.Errorln("could not persist nodekey: ", err)
+ glog.V(logger.Error).Infoln("could not persist nodekey: ", err)
}
return key, nil
}
@@ -177,7 +177,7 @@ func New(config *Config) (*Ethereum, error) {
return nil, fmt.Errorf("Database version mismatch. Protocol(%d / %d). `rm -rf %s`", protov, config.ProtocolVersion, path)
}
saveProtocolVersion(blockDb, config.ProtocolVersion)
- servlogger.Infof("Protocol Version: %v, Network Id: %v", config.ProtocolVersion, config.NetworkId)
+ glog.V(logger.Info).Infof("Protocol Version: %v, Network Id: %v", config.ProtocolVersion, config.NetworkId)
eth := &Ethereum{
shutdownChan: make(chan bool),
@@ -303,7 +303,7 @@ func (s *Ethereum) StartMining() error {
eb, err := s.Etherbase()
if err != nil {
err = fmt.Errorf("Cannot start mining without etherbase address: %v", err)
- servlogger.Errorln(err)
+ glog.V(logger.Error).Infoln(err)
return err
}
@@ -380,7 +380,7 @@ func (s *Ethereum) Start() error {
s.blockSub = s.eventMux.Subscribe(core.ChainHeadEvent{})
go s.blockBroadcastLoop()
- servlogger.Infoln("Server started")
+ glog.V(logger.Info).Infoln("Server started")
return nil
}
@@ -420,7 +420,7 @@ func (s *Ethereum) Stop() {
s.whisper.Stop()
}
- servlogger.Infoln("Server stopped")
+ glog.V(logger.Info).Infoln("Server stopped")
close(s.shutdownChan)
}
diff --git a/eth/protocol_test.go b/eth/protocol_test.go
index d3466326a..7c724f7a7 100644
--- a/eth/protocol_test.go
+++ b/eth/protocol_test.go
@@ -250,7 +250,7 @@ func TestNewBlockMsg(t *testing.T) {
var delay = 1 * time.Second
// eth.reset()
- block := types.NewBlock(common.Hash{1}, common.Address{1}, common.Hash{1}, common.Big1, 1, "extra")
+ block := types.NewBlock(common.Hash{1}, common.Address{1}, common.Hash{1}, common.Big1, 1, []byte("extra"))
go p2p.Send(eth, NewBlockMsg, &newBlockMsgData{Block: block})
timer := time.After(delay)
@@ -315,7 +315,7 @@ func TestBlockMsg(t *testing.T) {
var delay = 3 * time.Second
// eth.reset()
newblock := func(i int64) *types.Block {
- return types.NewBlock(common.Hash{byte(i)}, common.Address{byte(i)}, common.Hash{byte(i)}, big.NewInt(i), uint64(i), string(i))
+ return types.NewBlock(common.Hash{byte(i)}, common.Address{byte(i)}, common.Hash{byte(i)}, big.NewInt(i), uint64(i), []byte{byte(i)})
}
b := newblock(0)
b.Header().Difficulty = nil // check if nil as *big.Int decodes as 0
diff --git a/jsre/ethereum_js.go b/jsre/ethereum_js.go
index 0c38cd0e4..222ca27d6 100644
--- a/jsre/ethereum_js.go
+++ b/jsre/ethereum_js.go
@@ -1,4 +1,4 @@
package jsre
const Ethereum_JS = `
-require=function t(e,n,r){function o(a,s){if(!n[a]){if(!e[a]){var u="function"==typeof require&&require;if(!s&&u)return u(a,!0);if(i)return i(a,!0);var c=new Error("Cannot find module '"+a+"'");throw c.code="MODULE_NOT_FOUND",c}var l=n[a]={exports:{}};e[a][0].call(l.exports,function(t){var n=e[a][1][t];return o(n?n:t)},l,l.exports,t,e,n,r)}return n[a].exports}for(var i="function"==typeof require&&require,a=0;a<r.length;a++)o(r[a]);return o}({1:[function(t,e){var n=t("../utils/utils"),r=t("../utils/config"),o=t("./types"),i=t("./formatters"),a=function(t){throw new Error("parser does not support type: "+t)},s=function(t){return"[]"===t.slice(-2)},u=function(t,e){return s(t)||"bytes"===t?i.formatInputInt(e.length):""},c=o.inputTypes(),l=function(t,e){var n="",r="",o="";return t.forEach(function(t,r){n+=u(t.type,e[r])}),t.forEach(function(n,i){for(var u=!1,l=0;l<c.length&&!u;l++)u=c[l].type(t[i].type,e[i]);u||a(t[i].type);var f=c[l-1].format;s(t[i].type)?o+=e[i].reduce(function(t,e){return t+f(e)},""):"bytes"===t[i].type?o+=f(e[i]):r+=f(e[i])}),n+=r+o},f=function(t){return s(t)||"bytes"===t?2*r.ETH_PADDING:0},p=o.outputTypes(),m=function(t,e){e=e.slice(2);var n=[],u=2*r.ETH_PADDING,c=t.reduce(function(t,e){return t+f(e.type)},0),l=e.slice(0,c);return e=e.slice(c),t.forEach(function(r,c){for(var f=!1,m=0;m<p.length&&!f;m++)f=p[m].type(t[c].type);f||a(t[c].type);var h=p[m-1].format;if(s(t[c].type)){var d=i.formatOutputUInt(l.slice(0,u));l=l.slice(u);for(var g=[],v=0;d>v;v++)g.push(h(e.slice(0,u))),e=e.slice(u);n.push(g)}else o.prefixedType("bytes")(t[c].type)?(l=l.slice(u),n.push(h(e.slice(0,u))),e=e.slice(u)):(n.push(h(e.slice(0,u))),e=e.slice(u))}),n},h=function(t){var e={};return t.forEach(function(t){var r=n.extractDisplayName(t.name),o=n.extractTypeName(t.name),i=function(){var e=Array.prototype.slice.call(arguments);return l(t.inputs,e)};void 0===e[r]&&(e[r]=i),e[r][o]=i}),e},d=function(t){var e={};return t.forEach(function(t){var r=n.extractDisplayName(t.name),o=n.extractTypeName(t.name),i=function(e){return m(t.outputs,e)};void 0===e[r]&&(e[r]=i),e[r][o]=i}),e};e.exports={inputParser:h,outputParser:d,formatInput:l,formatOutput:m}},{"../utils/config":5,"../utils/utils":6,"./formatters":2,"./types":3}],2:[function(t,e){var n=t("bignumber.js"),r=t("../utils/utils"),o=t("../utils/config"),i=function(t){var e=2*o.ETH_PADDING;return n.config(o.ETH_BIGNUMBER_ROUNDING_MODE),r.padLeft(r.toTwosComplement(t).round().toString(16),e)},a=function(t){return r.fromAscii(t,o.ETH_PADDING).substr(2)},s=function(t){return"000000000000000000000000000000000000000000000000000000000000000"+(t?"1":"0")},u=function(t){return i(new n(t).times(new n(2).pow(128)))},c=function(t){return"1"===new n(t.substr(0,1),16).toString(2).substr(0,1)},l=function(t){return t=t||"0",c(t)?new n(t,16).minus(new n("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",16)).minus(1):new n(t,16)},f=function(t){return t=t||"0",new n(t,16)},p=function(t){return l(t).dividedBy(new n(2).pow(128))},m=function(t){return f(t).dividedBy(new n(2).pow(128))},h=function(t){return"0x"+t},d=function(t){return"0000000000000000000000000000000000000000000000000000000000000001"===t?!0:!1},g=function(t){return r.toAscii(t)},v=function(t){return"0x"+t.slice(t.length-40,t.length)};e.exports={formatInputInt:i,formatInputString:a,formatInputBool:s,formatInputReal:u,formatOutputInt:l,formatOutputUInt:f,formatOutputReal:p,formatOutputUReal:m,formatOutputHash:h,formatOutputBool:d,formatOutputString:g,formatOutputAddress:v}},{"../utils/config":5,"../utils/utils":6,"bignumber.js":"bignumber.js"}],3:[function(t,e){var n=t("./formatters"),r=function(t){return function(e){return 0===e.indexOf(t)}},o=function(t){return function(e){return t===e}},i=function(){return[{type:r("uint"),format:n.formatInputInt},{type:r("int"),format:n.formatInputInt},{type:r("bytes"),format:n.formatInputString},{type:r("real"),format:n.formatInputReal},{type:r("ureal"),format:n.formatInputReal},{type:o("address"),format:n.formatInputInt},{type:o("bool"),format:n.formatInputBool}]},a=function(){return[{type:r("uint"),format:n.formatOutputUInt},{type:r("int"),format:n.formatOutputInt},{type:r("bytes"),format:n.formatOutputString},{type:r("real"),format:n.formatOutputReal},{type:r("ureal"),format:n.formatOutputUReal},{type:o("address"),format:n.formatOutputAddress},{type:o("bool"),format:n.formatOutputBool}]};e.exports={prefixedType:r,namedType:o,inputTypes:i,outputTypes:a}},{"./formatters":2}],4:[function(t,e,n){"use strict";n.XMLHttpRequest="undefined"==typeof XMLHttpRequest?{}:XMLHttpRequest},{}],5:[function(t,e){var n=t("bignumber.js"),r=["wei","Kwei","Mwei","Gwei","szabo","finney","ether","grand","Mether","Gether","Tether","Pether","Eether","Zether","Yether","Nether","Dether","Vether","Uether"];e.exports={ETH_PADDING:32,ETH_SIGNATURE_LENGTH:4,ETH_UNITS:r,ETH_BIGNUMBER_ROUNDING_MODE:{ROUNDING_MODE:n.ROUND_DOWN},ETH_POLLING_TIMEOUT:1e3,ETH_DEFAULTBLOCK:"latest"}},{"bignumber.js":"bignumber.js"}],6:[function(t,e){var n=t("bignumber.js"),r={wei:"1",kwei:"1000",ada:"1000",mwei:"1000000",babbage:"1000000",gwei:"1000000000",shannon:"1000000000",szabo:"1000000000000",finney:"1000000000000000",ether:"1000000000000000000",kether:"1000000000000000000000",grand:"1000000000000000000000",einstein:"1000000000000000000000",mether:"1000000000000000000000000",gether:"1000000000000000000000000000",tether:"1000000000000000000000000000000"},o=function(t,e,n){return new Array(e-t.length+1).join(n?n:"0")+t},i=function(t,e){for(var n=!1,r=0;r<t.length&&!n;r++)n=e(t[r]);return n?r-1:-1},a=function(t){var e="",n=0,r=t.length;for("0x"===t.substring(0,2)&&(n=2);r>n;n+=2){var o=parseInt(t.substr(n,2),16);if(0===o)break;e+=String.fromCharCode(o)}return e},s=function(t){for(var e="",n=0;n<t.length;n++){var r=t.charCodeAt(n).toString(16);e+=r.length<2?"0"+r:r}return e},u=function(t,e){e=void 0===e?0:e;for(var n=s(t);n.length<2*e;)n+="00";return"0x"+n},c=function(t){var e=t.indexOf("(");return-1!==e?t.substr(0,e):t},l=function(t){var e=t.indexOf("(");return-1!==e?t.substr(e+1,t.length-1-(e+1)).replace(" ",""):""},f=function(t){return t.filter(function(t){return"function"===t.type})},p=function(t){return t.filter(function(t){return"event"===t.type})},m=function(t){return b(t).toNumber()},h=function(t){var e=b(t),n=e.toString(16);return e.lessThan(0)?"-0x"+n.substr(1):"0x"+n},d=function(t){if(O(t))return h(+t);if(F(t))return h(t);if(N(t))return u(JSON.stringify(t));if(_(t)){if(0===t.indexOf("-0x"))return h(t);if(!isFinite(t))return u(t)}return h(t)},g=function(t){t=t?t.toLowerCase():"ether";var e=r[t];if(void 0===e)throw new Error("This unit doesn't exists, please use the one of the following units"+JSON.stringify(r,null,2));return new n(e,10)},v=function(t,e){var n=b(t).dividedBy(g(e));return F(t)?n:n.toString(10)},y=function(t,e){var n=b(t).times(g(e));return F(t)?n:n.toString(10)},b=function(t){return t=t||0,F(t)?t:!_(t)||0!==t.indexOf("0x")&&0!==t.indexOf("-0x")?new n(t.toString(10),10):new n(t.replace("0x",""),16)},w=function(t){var e=b(t);return e.lessThan(0)?new n("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",16).plus(e).plus(1):e},x=function(t){return/^0x[0-9a-f]{40}$/.test(t)},I=function(t){return x(t)?t:/^[0-9a-f]{40}$/.test(t)?"0x"+t:"0x"+o(d(t).substr(2),40)},F=function(t){return t instanceof n||t&&t.constructor&&"BigNumber"===t.constructor.name},_=function(t){return"string"==typeof t||t&&t.constructor&&"String"===t.constructor.name},T=function(t){return"function"==typeof t},N=function(t){return"object"==typeof t},O=function(t){return"boolean"==typeof t},B=function(t){return t instanceof Array},D=function(t){try{return!!JSON.parse(t)}catch(e){return!1}};e.exports={padLeft:o,findIndex:i,toHex:d,toDecimal:m,fromDecimal:h,toAscii:a,fromAscii:u,extractDisplayName:c,extractTypeName:l,filterFunctions:f,filterEvents:p,toWei:y,fromWei:v,toBigNumber:b,toTwosComplement:w,toAddress:I,isBigNumber:F,isAddress:x,isFunction:T,isString:_,isObject:N,isBoolean:O,isArray:B,isJson:D}},{"bignumber.js":"bignumber.js"}],7:[function(t,e){e.exports={version:"0.2.2"}},{}],8:[function(t,e){var n=t("./version.json"),r=t("./web3/net"),o=t("./web3/eth"),i=t("./web3/db"),a=t("./web3/shh"),s=t("./web3/watches"),u=t("./web3/filter"),c=t("./utils/utils"),l=t("./web3/formatters"),f=t("./web3/requestmanager"),p=t("./utils/config"),m=t("./web3/method"),h=t("./web3/property"),d=[new m({name:"sha3",call:"web3_sha3",params:1})],g=[new h({name:"version.client",getter:"web3_clientVersion"}),new h({name:"version.network",getter:"net_version",inputFormatter:c.toDecimal}),new h({name:"version.ethereum",getter:"eth_version",inputFormatter:c.toDecimal}),new h({name:"version.whisper",getter:"shh_version",inputFormatter:c.toDecimal})],v=function(t,e){e.forEach(function(e){e.attachToObject(t)})},y=function(t,e){e.forEach(function(e){e.attachToObject(t)})},b={};b.providers={},b.version={},b.version.api=n.version,b.eth={},b.eth.filter=function(t,e,n,r){return t._isEvent?t(e,n):new u(t,s.eth(),r||l.outputLogFormatter)},b.shh={},b.shh.filter=function(t){return new u(t,s.shh(),l.outputPostFormatter)},b.net={},b.db={},b.setProvider=function(t){f.getInstance().setProvider(t)},b.reset=function(){f.getInstance().reset()},b.toHex=c.toHex,b.toAscii=c.toAscii,b.fromAscii=c.fromAscii,b.toDecimal=c.toDecimal,b.fromDecimal=c.fromDecimal,b.toBigNumber=c.toBigNumber,b.toWei=c.toWei,b.fromWei=c.fromWei,b.isAddress=c.isAddress,Object.defineProperty(b.eth,"defaultBlock",{get:function(){return p.ETH_DEFAULTBLOCK},set:function(t){return p.ETH_DEFAULTBLOCK=t,p.ETH_DEFAULTBLOCK}}),v(b,d),y(b,g),v(b.net,r.methods),y(b.net,r.properties),v(b.eth,o.methods),y(b.eth,o.properties),v(b.db,i.methods),v(b.shh,a.methods),e.exports=b},{"./utils/config":5,"./utils/utils":6,"./version.json":7,"./web3/db":10,"./web3/eth":12,"./web3/filter":14,"./web3/formatters":15,"./web3/method":18,"./web3/net":19,"./web3/property":20,"./web3/requestmanager":22,"./web3/shh":23,"./web3/watches":25}],9:[function(t,e){function n(t,e){t.forEach(function(t){if(-1===t.name.indexOf("(")){var e=t.name,n=t.inputs.map(function(t){return t.type}).join();t.name=e+"("+n+")"}});var n={};return u(n),c(n,t,e),l(n,t,e),f(n,t,e),n}var r=t("../web3"),o=t("../solidity/abi"),i=t("../utils/utils"),a=t("./event"),s=t("./signature"),u=function(t){t.call=function(e){return t._isTransaction=!1,t._options=e,t},t.sendTransaction=function(e){return t._isTransaction=!0,t._options=e,t}},c=function(t,e,n){var a=o.inputParser(e),u=o.outputParser(e);i.filterFunctions(e).forEach(function(e){var o=i.extractDisplayName(e.name),c=i.extractTypeName(e.name),l=function(){var i=Array.prototype.slice.call(arguments),l=s.functionSignatureFromAscii(e.name),f=a[o][c].apply(null,i),p=t._options||{};p.to=n,p.data=l+f;var m=t._isTransaction===!0||t._isTransaction!==!1&&!e.constant,h=p.collapse!==!1;if(t._options={},t._isTransaction=null,m)return void r.eth.sendTransaction(p);var d=r.eth.call(p),g=u[o][c](d);return h&&(1===g.length?g=g[0]:0===g.length&&(g=null)),g};void 0===t[o]&&(t[o]=l),t[o][c]=l})},l=function(t,e,n){t.address=n,t._onWatchEventResult=function(t){var n=event.getMatchingEvent(i.filterEvents(e)),r=a.outputParser(n);return r(t)},Object.defineProperty(t,"topics",{get:function(){return i.filterEvents(e).map(function(t){return s.eventSignatureFromAscii(t.name)})}})},f=function(t,e,n){i.filterEvents(e).forEach(function(e){var o=function(){var t=Array.prototype.slice.call(arguments),o=s.eventSignatureFromAscii(e.name),i=a.inputParser(n,o,e),u=i.apply(null,t),c=function(t){var n=a.outputParser(e);return n(t)};return r.eth.filter(u,void 0,void 0,c)};o._isEvent=!0;var u=i.extractDisplayName(e.name),c=i.extractTypeName(e.name);void 0===t[u]&&(t[u]=o),t[u][c]=o})},p=function(t){return n.bind(null,t)};e.exports=p},{"../solidity/abi":1,"../utils/utils":6,"../web3":8,"./event":13,"./signature":24}],10:[function(t,e){var n=t("./method"),r=new n({name:"putString",call:"db_putString",params:3}),o=new n({name:"getString",call:"db_getString",params:2}),i=new n({name:"putHex",call:"db_putHex",params:3}),a=new n({name:"getHex",call:"db_getHex",params:2}),s=[r,o,i,a];e.exports={methods:s}},{"./method":18}],11:[function(t,e){var n=t("../utils/utils");e.exports={InvalidNumberOfParams:new Error("Invalid number of input parameters"),InvalidProvider:new Error("Providor not set or invalid"),InvalidResponse:function(t){var e="Invalid JSON RPC response";return n.isObject(t)&&t.error&&t.error.message&&(e=t.error.message),new Error(e)}}},{"../utils/utils":6}],12:[function(t,e){"use strict";var n=t("./formatters"),r=t("../utils/utils"),o=t("./method"),i=t("./property"),a=function(t){return r.isString(t[0])&&0===t[0].indexOf("0x")?"eth_getBlockByHash":"eth_getBlockByNumber"},s=function(t){return r.isString(t[0])&&0===t[0].indexOf("0x")?"eth_getTransactionByBlockHashAndIndex":"eth_getTransactionByBlockNumberAndIndex"},u=function(t){return r.isString(t[0])&&0===t[0].indexOf("0x")?"eth_getUncleByBlockHashAndIndex":"eth_getUncleByBlockNumberAndIndex"},c=function(t){return r.isString(t[0])&&0===t[0].indexOf("0x")?"eth_getBlockTransactionCountByHash":"eth_getBlockTransactionCountByNumber"},l=function(t){return r.isString(t[0])&&0===t[0].indexOf("0x")?"eth_getUncleCountByBlockHash":"eth_getUncleCountByBlockNumber"},f=new o({name:"getBalance",call:"eth_getBalance",params:2,inputFormatter:[r.toAddress,n.inputDefaultBlockNumberFormatter],outputFormatter:n.outputBigNumberFormatter}),p=new o({name:"getStorageAt",call:"eth_getStorageAt",params:3,inputFormatter:[null,r.toHex,n.inputDefaultBlockNumberFormatter]}),m=new o({name:"getCode",call:"eth_getCode",params:2,inputFormatter:[r.toAddress,n.inputDefaultBlockNumberFormatter]}),h=new o({name:"getBlock",call:a,params:2,inputFormatter:[r.toHex,function(t){return!!t}],outputFormatter:n.outputBlockFormatter}),d=new o({name:"getUncle",call:u,params:3,inputFormatter:[r.toHex,r.toHex,function(t){return!!t}],outputFormatter:n.outputBlockFormatter}),g=new o({name:"getCompilers",call:"eth_getCompilers",params:0}),v=new o({name:"getBlockTransactionCount",call:c,params:1,inputFormatter:[r.toHex],outputFormatter:r.toDecimal}),y=new o({name:"getBlockUncleCount",call:l,params:1,inputFormatter:[r.toHex],outputFormatter:r.toDecimal}),b=new o({name:"getTransaction",call:"eth_getTransactionByHash",params:1,outputFormatter:n.outputTransactionFormatter}),w=new o({name:"getTransactionFromBlock",call:s,params:2,inputFormatter:[r.toHex,r.toHex],outputFormatter:n.outputTransactionFormatter}),x=new o({name:"getTransactionCount",call:"eth_getTransactionCount",params:2,inputFormatter:[null,n.inputDefaultBlockNumberFormatter],outputFormatter:r.toDecimal}),I=new o({name:"sendTransaction",call:"eth_sendTransaction",params:1,inputFormatter:[n.inputTransactionFormatter]}),F=new o({name:"call",call:"eth_call",params:2,inputFormatter:[n.inputTransactionFormatter,n.inputDefaultBlockNumberFormatter]}),_=new o({name:"compile.solidity",call:"eth_compileSolidity",params:1}),T=new o({name:"compile.lll",call:"eth_compileLLL",params:1}),N=new o({name:"compile.serpent",call:"eth_compileSerpent",params:1}),O=new o({name:"flush",call:"eth_flush",params:0}),B=[f,p,m,h,d,g,v,y,b,w,x,F,I,_,T,N,O],D=[new i({name:"coinbase",getter:"eth_coinbase"}),new i({name:"mining",getter:"eth_mining"}),new i({name:"gasPrice",getter:"eth_gasPrice",outputFormatter:n.inputNumberFormatter}),new i({name:"accounts",getter:"eth_accounts"}),new i({name:"blockNumber",getter:"eth_blockNumber",outputFormatter:r.toDecimal})];e.exports={methods:B,properties:D}},{"../utils/utils":6,"./formatters":15,"./method":18,"./property":20}],13:[function(t,e){var n=t("../solidity/abi"),r=t("../utils/utils"),o=t("./signature"),i=function(t,e){return t.filter(function(t){return t.indexed===e})},a=function(t,e){var n=r.findIndex(t,function(t){return t.name===e});return-1===n?void console.error("indexed param with name "+e+" not found"):t[n]},s=function(t,e){return Object.keys(e).map(function(r){var o=[a(i(t.inputs,!0),r)],s=e[r];return s instanceof Array?s.map(function(t){return n.formatInput(o,[t])}):"0x"+n.formatInput(o,[s])})},u=function(t,e,n){return function(r,o){var i=o||{};return i.address=t,i.topics=[],i.topics.push(e),r&&(i.topics=i.topics.concat(s(n,r))),i}},c=function(t,e,n){var r=e.slice(),o=n.slice();return t.reduce(function(t,e){var n;return n=e.indexed?r.splice(0,1)[0]:o.splice(0,1)[0],t[e.name]=n,t},{})},l=function(t){return function(e){var o={event:r.extractDisplayName(t.name),number:e.number,hash:e.hash,args:{}};if(!e.topics)return o;e.data=e.data||"";var a=i(t.inputs,!0),s="0x"+e.topics.slice(1,e.topics.length).map(function(t){return t.slice(2)}).join(""),u=n.formatOutput(a,s),l=i(t.inputs,!1),f=n.formatOutput(l,e.data);return o.args=c(t.inputs,u,f),o}},f=function(t,e){for(var n=0;n<t.length;n++){var r=o.eventSignatureFromAscii(t[n].name);if(r===e.topics[0])return t[n]}return void 0};e.exports={inputParser:u,outputParser:l,getMatchingEvent:f}},{"../solidity/abi":1,"../utils/utils":6,"./signature":24}],14:[function(t,e){var n=t("./requestmanager"),r=t("./formatters"),o=t("../utils/utils"),i=function(t){return o.isString(t)?t:(t=t||{},t.topics=t.topics||[],t.topics=t.topics.map(function(t){return o.toHex(t)}),{topics:t.topics,to:t.to,address:t.address,fromBlock:r.inputBlockNumberFormatter(t.fromBlock),toBlock:r.inputBlockNumberFormatter(t.toBlock)})},a=function(t,e,n){var r={};e.forEach(function(t){t.attachToObject(r)}),this.options=i(t),this.implementation=r,this.callbacks=[],this.formatter=n,this.filterId=this.implementation.newFilter(this.options)};a.prototype.watch=function(t){this.callbacks.push(t);var e=this,r=function(t,n){return t?e.callbacks.forEach(function(e){e(t)}):void n.forEach(function(t){t=e.formatter?e.formatter(t):t,e.callbacks.forEach(function(e){e(null,t)})})};n.getInstance().startPolling({method:this.implementation.poll.call,params:[this.filterId]},this.filterId,r,this.stopWatching.bind(this))},a.prototype.stopWatching=function(){n.getInstance().stopPolling(this.filterId),this.implementation.uninstallFilter(this.filterId),this.callbacks=[]},a.prototype.get=function(){var t=this.implementation.getLogs(this.filterId),e=this;return t.map(function(t){return e.formatter?e.formatter(t):t})},e.exports=a},{"../utils/utils":6,"./formatters":15,"./requestmanager":22}],15:[function(t,e){var n=t("../utils/utils"),r=t("../utils/config"),o=function(t){return n.toBigNumber(t)},i=function(t){return"latest"===t||"pending"===t||"earliest"===t},a=function(t){return void 0===t?r.ETH_DEFAULTBLOCK:s(t)},s=function(t){return void 0===t?void 0:i(t)?t:n.toHex(t)},u=function(t){return t.code&&(t.data=t.code,delete t.code),["gasPrice","gas","value"].filter(function(e){return void 0!==t[e]}).forEach(function(e){t[e]=n.fromDecimal(t[e])}),t},c=function(t){return t.blockNumber=n.toDecimal(t.blockNumber),t.transactionIndex=n.toDecimal(t.transactionIndex),t.gas=n.toDecimal(t.gas),t.gasPrice=n.toBigNumber(t.gasPrice),t.value=n.toBigNumber(t.value),t},l=function(t){return t.gasLimit=n.toDecimal(t.gasLimit),t.gasUsed=n.toDecimal(t.gasUsed),t.size=n.toDecimal(t.size),t.timestamp=n.toDecimal(t.timestamp),t.number=n.toDecimal(t.number),t.minGasPrice=n.toBigNumber(t.minGasPrice),t.difficulty=n.toBigNumber(t.difficulty),t.totalDifficulty=n.toBigNumber(t.totalDifficulty),n.isArray(t.transactions)&&t.transactions.forEach(function(t){return n.isString(t)?void 0:c(t)}),t},f=function(t){return null===t?null:(t.blockNumber=n.toDecimal(t.blockNumber),t.transactionIndex=n.toDecimal(t.transactionIndex),t.logIndex=n.toDecimal(t.logIndex),t)},p=function(t){return t.payload=n.toHex(t.payload),t.ttl=n.fromDecimal(t.ttl),t.priority=n.fromDecimal(t.priority),n.isArray(t.topics)||(t.topics=[t.topics]),t.topics=t.topics.map(function(t){return n.fromAscii(t)}),t},m=function(t){return t.expiry=n.toDecimal(t.expiry),t.sent=n.toDecimal(t.sent),t.ttl=n.toDecimal(t.ttl),t.workProved=n.toDecimal(t.workProved),t.payloadRaw=t.payload,t.payload=n.toAscii(t.payload),n.isJson(t.payload)&&(t.payload=JSON.parse(t.payload)),t.topics=t.topics.map(function(t){return n.toAscii(t)}),t};e.exports={inputDefaultBlockNumberFormatter:a,inputBlockNumberFormatter:s,inputTransactionFormatter:u,inputPostFormatter:p,outputBigNumberFormatter:o,outputTransactionFormatter:c,outputBlockFormatter:l,outputLogFormatter:f,outputPostFormatter:m}},{"../utils/config":5,"../utils/utils":6}],16:[function(t,e){"use strict";var n=t("xmlhttprequest").XMLHttpRequest,r=function(t){this.host=t||"http://localhost:8080"};r.prototype.send=function(t){var e=new n;return e.open("POST",this.host,!1),e.send(JSON.stringify(t)),JSON.parse(e.responseText)},r.prototype.sendAsync=function(t,e){var r=new n;r.onreadystatechange=function(){4===r.readyState&&e(null,JSON.parse(r.responseText))},r.open("POST",this.host,!0),r.send(JSON.stringify(t))},e.exports=r},{xmlhttprequest:4}],17:[function(t,e){var n=function(){return arguments.callee._singletonInstance?arguments.callee._singletonInstance:(arguments.callee._singletonInstance=this,void(this.messageId=1))};n.getInstance=function(){var t=new n;return t},n.prototype.toPayload=function(t,e){return t||console.error("jsonrpc method should be specified!"),{jsonrpc:"2.0",method:t,params:e||[],id:this.messageId++}},n.prototype.isValidResponse=function(t){return!!t&&!t.error&&"2.0"===t.jsonrpc&&"number"==typeof t.id&&void 0!==t.result},n.prototype.toBatchPayload=function(t){var e=this;return t.map(function(t){return e.toPayload(t.method,t.params)})},e.exports=n},{}],18:[function(t,e){var n=t("./requestmanager"),r=t("../utils/utils"),o=t("./errors"),i=function(t){this.name=t.name,this.call=t.call,this.params=t.params||0,this.inputFormatter=t.inputFormatter,this.outputFormatter=t.outputFormatter};i.prototype.getCall=function(t){return r.isFunction(this.call)?this.call(t):this.call},i.prototype.extractCallback=function(t){return r.isFunction(t[t.length-1])?t.pop():null},i.prototype.validateArgs=function(t){if(t.length!==this.params)throw o.InvalidNumberOfParams},i.prototype.formatInput=function(t){return this.inputFormatter?this.inputFormatter.map(function(e,n){return e?e(t[n]):t[n]}):t},i.prototype.formatOutput=function(t){return this.outputFormatter&&null!==t?this.outputFormatter(t):t},i.prototype.attachToObject=function(t){var e=this.send.bind(this);e.call=this.call;var n=this.name.split(".");n.length>1?(t[n[0]]=t[n[0]]||{},t[n[0]][n[1]]=e):t[n[0]]=e},i.prototype.toPayload=function(t){var e=this.getCall(t),n=this.extractCallback(t),r=this.formatInput(t);return this.validateArgs(r),{method:e,params:r,callback:n}},i.prototype.send=function(){var t=this.toPayload(Array.prototype.slice.call(arguments));if(t.callback){var e=this;return n.getInstance().sendAsync(t,function(n,r){t.callback(null,e.formatOutput(r))})}return this.formatOutput(n.getInstance().send(t))},e.exports=i},{"../utils/utils":6,"./errors":11,"./requestmanager":22}],19:[function(t,e){var n=t("../utils/utils"),r=t("./property"),o=[],i=[new r({name:"listening",getter:"net_listening"}),new r({name:"peerCount",getter:"net_peerCount",outputFormatter:n.toDecimal})];e.exports={methods:o,properties:i}},{"../utils/utils":6,"./property":20}],20:[function(t,e){var n=t("./requestmanager"),r=function(t){this.name=t.name,this.getter=t.getter,this.setter=t.setter,this.outputFormatter=t.outputFormatter,this.inputFormatter=t.inputFormatter};r.prototype.formatInput=function(t){return this.inputFormatter?this.inputFormatter(t):t},r.prototype.formatOutput=function(t){return this.outputFormatter&&null!==t?this.outputFormatter(t):t},r.prototype.attachToObject=function(t){var e={get:this.get.bind(this),set:this.set.bind(this)},n=this.name.split(".");n.length>1?(t[n[0]]=t[n[0]]||{},Object.defineProperty(t[n[0]],n[1],e)):Object.defineProperty(t,n[0],e)},r.prototype.get=function(){return this.formatOutput(n.getInstance().send({method:this.getter}))},r.prototype.set=function(t){return n.getInstance().send({method:this.setter,params:[this.formatInput(t)]})},e.exports=r},{"./requestmanager":22}],21:[function(t,e){var n=function(){};n.prototype.send=function(t){var e=navigator.qt.callMethod(JSON.stringify(t));return JSON.parse(e)},e.exports=n},{}],22:[function(t,e){var n=t("./jsonrpc"),r=t("../utils/utils"),o=t("../utils/config"),i=t("./errors"),a=function(t){return arguments.callee._singletonInstance?arguments.callee._singletonInstance:(arguments.callee._singletonInstance=this,this.provider=t,this.polls=[],this.timeout=null,void this.poll())};a.getInstance=function(){var t=new a;return t},a.prototype.send=function(t){if(!this.provider)return console.error(i.InvalidProvider),null;var e=n.getInstance().toPayload(t.method,t.params),r=this.provider.send(e);if(!n.getInstance().isValidResponse(r))throw i.InvalidResponse(r);return r.result},a.prototype.sendAsync=function(t,e){if(!this.provider)return e(i.InvalidProvider);var r=n.getInstance().toPayload(t.method,t.params);this.provider.sendAsync(r,function(t,r){return t?e(t):n.getInstance().isValidResponse(r)?void e(null,r.result):e(i.InvalidResponse(r))})},a.prototype.setProvider=function(t){this.provider=t},a.prototype.startPolling=function(t,e,n,r){this.polls.push({data:t,id:e,callback:n,uninstall:r})},a.prototype.stopPolling=function(t){for(var e=this.polls.length;e--;){var n=this.polls[e];n.id===t&&this.polls.splice(e,1)}},a.prototype.reset=function(){this.polls.forEach(function(t){t.uninstall(t.id)}),this.polls=[],this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.poll()},a.prototype.poll=function(){if(this.timeout=setTimeout(this.poll.bind(this),o.ETH_POLLING_TIMEOUT),this.polls.length){if(!this.provider)return void console.error(i.InvalidProvider);var t=n.getInstance().toBatchPayload(this.polls.map(function(t){return t.data})),e=this;this.provider.sendAsync(t,function(t,o){if(!t){if(!r.isArray(o))throw i.InvalidResponse(o);o.map(function(t,n){return t.callback=e.polls[n].callback,t}).filter(function(t){var e=n.getInstance().isValidResponse(t);return e||t.callback(i.InvalidResponse(t)),e}).filter(function(t){return r.isArray(t.result)&&t.result.length>0}).forEach(function(t){t.callback(null,t.result)})}})}},e.exports=a},{"../utils/config":5,"../utils/utils":6,"./errors":11,"./jsonrpc":17}],23:[function(t,e){var n=t("./method"),r=t("./formatters"),o=new n({name:"post",call:"shh_post",params:1,inputFormatter:r.inputPostFormatter}),i=new n({name:"newIdentity",call:"shh_newIdentity",params:0}),a=new n({name:"hasIdentity",call:"shh_hasIdentity",params:1}),s=new n({name:"newGroup",call:"shh_newGroup",params:0}),u=new n({name:"addToGroup",call:"shh_addToGroup",params:0}),c=[o,i,a,s,u];e.exports={methods:c}},{"./formatters":15,"./method":18}],24:[function(t,e){var n=t("../web3"),r=t("../utils/config"),o=function(t){return n.sha3(n.fromAscii(t)).slice(0,2+2*r.ETH_SIGNATURE_LENGTH)},i=function(t){return n.sha3(n.fromAscii(t))};e.exports={functionSignatureFromAscii:o,eventSignatureFromAscii:i}},{"../utils/config":5,"../web3":8}],25:[function(t,e){var n=t("./method"),r=function(){var t=function(t){return"string"==typeof t[0]?"eth_newBlockFilter":"eth_newFilter"},e=new n({name:"newFilter",call:t,params:1}),r=new n({name:"uninstallFilter",call:"eth_uninstallFilter",params:1}),o=new n({name:"getLogs",call:"eth_getFilterLogs",params:1}),i=new n({name:"poll",call:"eth_getFilterChanges",params:1});return[e,r,o,i]},o=function(){var t=new n({name:"newFilter",call:"shh_newFilter",params:1}),e=new n({name:"uninstallFilter",call:"shh_uninstallFilter",params:1}),r=new n({name:"getLogs",call:"shh_getMessages",params:1}),o=new n({name:"poll",call:"shh_getFilterChanges",params:1});return[t,e,r,o]};e.exports={eth:r,shh:o}},{"./method":18}],26:[function(){},{}],"bignumber.js":[function(t,e){"use strict";e.exports=BigNumber},{}],"ethereum.js":[function(t,e){var n=t("./lib/web3");n.providers.HttpProvider=t("./lib/web3/httpprovider"),n.providers.QtSyncProvider=t("./lib/web3/qtsync"),n.eth.contract=t("./lib/web3/contract"),n.abi=t("./lib/solidity/abi"),e.exports=n},{"./lib/solidity/abi":1,"./lib/web3":8,"./lib/web3/contract":9,"./lib/web3/httpprovider":16,"./lib/web3/qtsync":21}]},{},["ethereum.js"]);`
+require=function t(e,n,r){function o(a,u){if(!n[a]){if(!e[a]){var s="function"==typeof require&&require;if(!u&&s)return s(a,!0);if(i)return i(a,!0);var c=new Error("Cannot find module '"+a+"'");throw c.code="MODULE_NOT_FOUND",c}var l=n[a]={exports:{}};e[a][0].call(l.exports,function(t){var n=e[a][1][t];return o(n?n:t)},l,l.exports,t,e,n,r)}return n[a].exports}for(var i="function"==typeof require&&require,a=0;a<r.length;a++)o(r[a]);return o}({1:[function(t,e){var n=t("../utils/utils"),r=t("../utils/config"),o=t("./types"),i=t("./formatters"),a=function(t){throw new Error("parser does not support type: "+t)},u=function(t){return"[]"===t.slice(-2)},s=function(t,e){return u(t)||"bytes"===t?i.formatInputInt(e.length):""},c=o.inputTypes(),l=function(t,e){var n="",r="",o="";return t.forEach(function(t,r){n+=s(t.type,e[r])}),t.forEach(function(n,i){for(var s=!1,l=0;l<c.length&&!s;l++)s=c[l].type(t[i].type,e[i]);s||a(t[i].type);var f=c[l-1].format;u(t[i].type)?o+=e[i].reduce(function(t,e){return t+f(e)},""):"bytes"===t[i].type?o+=f(e[i]):r+=f(e[i])}),n+=r+o},f=function(t){return u(t)||"bytes"===t?2*r.ETH_PADDING:0},p=o.outputTypes(),m=function(t,e){e=e.slice(2);var n=[],s=2*r.ETH_PADDING,c=t.reduce(function(t,e){return t+f(e.type)},0),l=e.slice(0,c);return e=e.slice(c),t.forEach(function(r,c){for(var f=!1,m=0;m<p.length&&!f;m++)f=p[m].type(t[c].type);f||a(t[c].type);var h=p[m-1].format;if(u(t[c].type)){var d=i.formatOutputUInt(l.slice(0,s));l=l.slice(s);for(var g=[],v=0;d>v;v++)g.push(h(e.slice(0,s))),e=e.slice(s);n.push(g)}else o.prefixedType("bytes")(t[c].type)?(l=l.slice(s),n.push(h(e.slice(0,s))),e=e.slice(s)):(n.push(h(e.slice(0,s))),e=e.slice(s))}),n},h=function(t){var e={};return t.forEach(function(t){var r=n.extractDisplayName(t.name),o=n.extractTypeName(t.name),i=function(){var e=Array.prototype.slice.call(arguments);return l(t.inputs,e)};void 0===e[r]&&(e[r]=i),e[r][o]=i}),e},d=function(t){var e={};return t.forEach(function(t){var r=n.extractDisplayName(t.name),o=n.extractTypeName(t.name),i=function(e){return m(t.outputs,e)};void 0===e[r]&&(e[r]=i),e[r][o]=i}),e};e.exports={inputParser:h,outputParser:d,formatInput:l,formatOutput:m}},{"../utils/config":5,"../utils/utils":6,"./formatters":2,"./types":3}],2:[function(t,e){var n=t("bignumber.js"),r=t("../utils/utils"),o=t("../utils/config"),i=function(t){var e=2*o.ETH_PADDING;return n.config(o.ETH_BIGNUMBER_ROUNDING_MODE),r.padLeft(r.toTwosComplement(t).round().toString(16),e)},a=function(t){return r.fromAscii(t,o.ETH_PADDING).substr(2)},u=function(t){return"000000000000000000000000000000000000000000000000000000000000000"+(t?"1":"0")},s=function(t){return i(new n(t).times(new n(2).pow(128)))},c=function(t){return"1"===new n(t.substr(0,1),16).toString(2).substr(0,1)},l=function(t){return t=t||"0",c(t)?new n(t,16).minus(new n("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",16)).minus(1):new n(t,16)},f=function(t){return t=t||"0",new n(t,16)},p=function(t){return l(t).dividedBy(new n(2).pow(128))},m=function(t){return f(t).dividedBy(new n(2).pow(128))},h=function(t){return"0x"+t},d=function(t){return"0000000000000000000000000000000000000000000000000000000000000001"===t?!0:!1},g=function(t){return r.toAscii(t)},v=function(t){return"0x"+t.slice(t.length-40,t.length)};e.exports={formatInputInt:i,formatInputString:a,formatInputBool:u,formatInputReal:s,formatOutputInt:l,formatOutputUInt:f,formatOutputReal:p,formatOutputUReal:m,formatOutputHash:h,formatOutputBool:d,formatOutputString:g,formatOutputAddress:v}},{"../utils/config":5,"../utils/utils":6,"bignumber.js":"bignumber.js"}],3:[function(t,e){var n=t("./formatters"),r=function(t){return function(e){return 0===e.indexOf(t)}},o=function(t){return function(e){return t===e}},i=function(){return[{type:r("uint"),format:n.formatInputInt},{type:r("int"),format:n.formatInputInt},{type:r("bytes"),format:n.formatInputString},{type:r("real"),format:n.formatInputReal},{type:r("ureal"),format:n.formatInputReal},{type:o("address"),format:n.formatInputInt},{type:o("bool"),format:n.formatInputBool}]},a=function(){return[{type:r("uint"),format:n.formatOutputUInt},{type:r("int"),format:n.formatOutputInt},{type:r("bytes"),format:n.formatOutputString},{type:r("real"),format:n.formatOutputReal},{type:r("ureal"),format:n.formatOutputUReal},{type:o("address"),format:n.formatOutputAddress},{type:o("bool"),format:n.formatOutputBool}]};e.exports={prefixedType:r,namedType:o,inputTypes:i,outputTypes:a}},{"./formatters":2}],4:[function(t,e,n){"use strict";n.XMLHttpRequest="undefined"==typeof XMLHttpRequest?{}:XMLHttpRequest},{}],5:[function(t,e){var n=t("bignumber.js"),r=["wei","Kwei","Mwei","Gwei","szabo","finney","ether","grand","Mether","Gether","Tether","Pether","Eether","Zether","Yether","Nether","Dether","Vether","Uether"];e.exports={ETH_PADDING:32,ETH_SIGNATURE_LENGTH:4,ETH_UNITS:r,ETH_BIGNUMBER_ROUNDING_MODE:{ROUNDING_MODE:n.ROUND_DOWN},ETH_POLLING_TIMEOUT:1e3,ETH_DEFAULTBLOCK:"latest"}},{"bignumber.js":"bignumber.js"}],6:[function(t,e){var n=t("bignumber.js"),r={wei:"1",kwei:"1000",ada:"1000",mwei:"1000000",babbage:"1000000",gwei:"1000000000",shannon:"1000000000",szabo:"1000000000000",finney:"1000000000000000",ether:"1000000000000000000",kether:"1000000000000000000000",grand:"1000000000000000000000",einstein:"1000000000000000000000",mether:"1000000000000000000000000",gether:"1000000000000000000000000000",tether:"1000000000000000000000000000000"},o=function(t,e,n){return new Array(e-t.length+1).join(n?n:"0")+t},i=function(t,e){for(var n=!1,r=0;r<t.length&&!n;r++)n=e(t[r]);return n?r-1:-1},a=function(t){var e="",n=0,r=t.length;for("0x"===t.substring(0,2)&&(n=2);r>n;n+=2){var o=parseInt(t.substr(n,2),16);if(0===o)break;e+=String.fromCharCode(o)}return e},u=function(t){for(var e="",n=0;n<t.length;n++){var r=t.charCodeAt(n).toString(16);e+=r.length<2?"0"+r:r}return e},s=function(t,e){e=void 0===e?0:e;for(var n=u(t);n.length<2*e;)n+="00";return"0x"+n},c=function(t){var e=t.indexOf("(");return-1!==e?t.substr(0,e):t},l=function(t){var e=t.indexOf("(");return-1!==e?t.substr(e+1,t.length-1-(e+1)).replace(" ",""):""},f=function(t){return t.filter(function(t){return"function"===t.type})},p=function(t){return t.filter(function(t){return"event"===t.type})},m=function(t){return y(t).toNumber()},h=function(t){var e=y(t),n=e.toString(16);return e.lessThan(0)?"-0x"+n.substr(1):"0x"+n},d=function(t){if(O(t))return h(+t);if(F(t))return h(t);if(N(t))return s(JSON.stringify(t));if(_(t)){if(0===t.indexOf("-0x"))return h(t);if(!isFinite(t))return s(t)}return h(t)},g=function(t){t=t?t.toLowerCase():"ether";var e=r[t];if(void 0===e)throw new Error("This unit doesn't exists, please use the one of the following units"+JSON.stringify(r,null,2));return new n(e,10)},v=function(t,e){var n=y(t).dividedBy(g(e));return F(t)?n:n.toString(10)},b=function(t,e){var n=y(t).times(g(e));return F(t)?n:n.toString(10)},y=function(t){return t=t||0,F(t)?t:!_(t)||0!==t.indexOf("0x")&&0!==t.indexOf("-0x")?new n(t.toString(10),10):new n(t.replace("0x",""),16)},w=function(t){var e=y(t);return e.lessThan(0)?new n("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",16).plus(e).plus(1):e},x=function(t){return/^0x[0-9a-f]{40}$/.test(t)},I=function(t){return x(t)?t:/^[0-9a-f]{40}$/.test(t)?"0x"+t:"0x"+o(d(t).substr(2),40)},F=function(t){return t instanceof n||t&&t.constructor&&"BigNumber"===t.constructor.name},_=function(t){return"string"==typeof t||t&&t.constructor&&"String"===t.constructor.name},T=function(t){return"function"==typeof t},N=function(t){return"object"==typeof t},O=function(t){return"boolean"==typeof t},B=function(t){return t instanceof Array},D=function(t){try{return!!JSON.parse(t)}catch(e){return!1}};e.exports={padLeft:o,findIndex:i,toHex:d,toDecimal:m,fromDecimal:h,toAscii:a,fromAscii:s,extractDisplayName:c,extractTypeName:l,filterFunctions:f,filterEvents:p,toWei:b,fromWei:v,toBigNumber:y,toTwosComplement:w,toAddress:I,isBigNumber:F,isAddress:x,isFunction:T,isString:_,isObject:N,isBoolean:O,isArray:B,isJson:D}},{"bignumber.js":"bignumber.js"}],7:[function(t,e){e.exports={version:"0.2.4"}},{}],8:[function(t,e){var n=t("./version.json"),r=t("./web3/net"),o=t("./web3/eth"),i=t("./web3/db"),a=t("./web3/shh"),u=t("./web3/watches"),s=t("./web3/filter"),c=t("./utils/utils"),l=t("./web3/formatters"),f=t("./web3/requestmanager"),p=t("./utils/config"),m=t("./web3/method"),h=t("./web3/property"),d=[new m({name:"sha3",call:"web3_sha3",params:1})],g=[new h({name:"version.client",getter:"web3_clientVersion"}),new h({name:"version.network",getter:"net_version",inputFormatter:c.toDecimal}),new h({name:"version.ethereum",getter:"eth_version",inputFormatter:c.toDecimal}),new h({name:"version.whisper",getter:"shh_version",inputFormatter:c.toDecimal})],v=function(t,e){e.forEach(function(e){e.attachToObject(t)})},b=function(t,e){e.forEach(function(e){e.attachToObject(t)})},y={};y.providers={},y.version={},y.version.api=n.version,y.eth={},y.eth.filter=function(t,e,n,r){return t._isEvent?t(e,n):new s(t,u.eth(),r||l.outputLogFormatter)},y.shh={},y.shh.filter=function(t){return new s(t,u.shh(),l.outputPostFormatter)},y.net={},y.db={},y.setProvider=function(t){f.getInstance().setProvider(t)},y.reset=function(){f.getInstance().reset()},y.toHex=c.toHex,y.toAscii=c.toAscii,y.fromAscii=c.fromAscii,y.toDecimal=c.toDecimal,y.fromDecimal=c.fromDecimal,y.toBigNumber=c.toBigNumber,y.toWei=c.toWei,y.fromWei=c.fromWei,y.isAddress=c.isAddress,Object.defineProperty(y.eth,"defaultBlock",{get:function(){return p.ETH_DEFAULTBLOCK},set:function(t){return p.ETH_DEFAULTBLOCK=t,p.ETH_DEFAULTBLOCK}}),v(y,d),b(y,g),v(y.net,r.methods),b(y.net,r.properties),v(y.eth,o.methods),b(y.eth,o.properties),v(y.db,i.methods),v(y.shh,a.methods),e.exports=y},{"./utils/config":5,"./utils/utils":6,"./version.json":7,"./web3/db":10,"./web3/eth":12,"./web3/filter":14,"./web3/formatters":15,"./web3/method":18,"./web3/net":19,"./web3/property":20,"./web3/requestmanager":22,"./web3/shh":23,"./web3/watches":25}],9:[function(t,e){function n(t,e){t.forEach(function(t){if(-1===t.name.indexOf("(")){var e=t.name,n=t.inputs.map(function(t){return t.type}).join();t.name=e+"("+n+")"}});var n={};return s(n),c(n,t,e),l(n,t,e),f(n,t,e),n}var r=t("../web3"),o=t("../solidity/abi"),i=t("../utils/utils"),a=t("./event"),u=t("./signature"),s=function(t){t.call=function(e){return t._isTransaction=!1,t._options=e,t},t.sendTransaction=function(e){return t._isTransaction=!0,t._options=e,t}},c=function(t,e,n){var a=o.inputParser(e),s=o.outputParser(e);i.filterFunctions(e).forEach(function(e){var o=i.extractDisplayName(e.name),c=i.extractTypeName(e.name),l=function(){var i=Array.prototype.slice.call(arguments),l=u.functionSignatureFromAscii(e.name),f=a[o][c].apply(null,i),p=t._options||{};p.to=n,p.data=l+f;var m=t._isTransaction===!0||t._isTransaction!==!1&&!e.constant,h=p.collapse!==!1;if(t._options={},t._isTransaction=null,m)return void r.eth.sendTransaction(p);var d=r.eth.call(p),g=s[o][c](d);return h&&(1===g.length?g=g[0]:0===g.length&&(g=null)),g};void 0===t[o]&&(t[o]=l),t[o][c]=l})},l=function(t,e,n){t.address=n,t._onWatchEventResult=function(t){var n=event.getMatchingEvent(i.filterEvents(e)),r=a.outputParser(n);return r(t)},Object.defineProperty(t,"topics",{get:function(){return i.filterEvents(e).map(function(t){return u.eventSignatureFromAscii(t.name)})}})},f=function(t,e,n){i.filterEvents(e).forEach(function(e){var o=function(){var t=Array.prototype.slice.call(arguments),o=u.eventSignatureFromAscii(e.name),i=a.inputParser(n,o,e),s=i.apply(null,t),c=function(t){var n=a.outputParser(e);return n(t)};return r.eth.filter(s,void 0,void 0,c)};o._isEvent=!0;var s=i.extractDisplayName(e.name),c=i.extractTypeName(e.name);void 0===t[s]&&(t[s]=o),t[s][c]=o})},p=function(t){return n.bind(null,t)};e.exports=p},{"../solidity/abi":1,"../utils/utils":6,"../web3":8,"./event":13,"./signature":24}],10:[function(t,e){var n=t("./method"),r=new n({name:"putString",call:"db_putString",params:3}),o=new n({name:"getString",call:"db_getString",params:2}),i=new n({name:"putHex",call:"db_putHex",params:3}),a=new n({name:"getHex",call:"db_getHex",params:2}),u=[r,o,i,a];e.exports={methods:u}},{"./method":18}],11:[function(t,e){var n=t("../utils/utils");e.exports={InvalidNumberOfParams:new Error("Invalid number of input parameters"),InvalidProvider:new Error("Providor not set or invalid"),InvalidResponse:function(t){var e="Invalid JSON RPC response";return n.isObject(t)&&t.error&&t.error.message&&(e=t.error.message),new Error(e)}}},{"../utils/utils":6}],12:[function(t,e){"use strict";var n=t("./formatters"),r=t("../utils/utils"),o=t("./method"),i=t("./property"),a=function(t){return r.isString(t[0])&&0===t[0].indexOf("0x")?"eth_getBlockByHash":"eth_getBlockByNumber"},u=function(t){return r.isString(t[0])&&0===t[0].indexOf("0x")?"eth_getTransactionByBlockHashAndIndex":"eth_getTransactionByBlockNumberAndIndex"},s=function(t){return r.isString(t[0])&&0===t[0].indexOf("0x")?"eth_getUncleByBlockHashAndIndex":"eth_getUncleByBlockNumberAndIndex"},c=function(t){return r.isString(t[0])&&0===t[0].indexOf("0x")?"eth_getBlockTransactionCountByHash":"eth_getBlockTransactionCountByNumber"},l=function(t){return r.isString(t[0])&&0===t[0].indexOf("0x")?"eth_getUncleCountByBlockHash":"eth_getUncleCountByBlockNumber"},f=new o({name:"getBalance",call:"eth_getBalance",params:2,inputFormatter:[r.toAddress,n.inputDefaultBlockNumberFormatter],outputFormatter:n.outputBigNumberFormatter}),p=new o({name:"getStorageAt",call:"eth_getStorageAt",params:3,inputFormatter:[null,r.toHex,n.inputDefaultBlockNumberFormatter]}),m=new o({name:"getCode",call:"eth_getCode",params:2,inputFormatter:[r.toAddress,n.inputDefaultBlockNumberFormatter]}),h=new o({name:"getBlock",call:a,params:2,inputFormatter:[r.toHex,function(t){return!!t}],outputFormatter:n.outputBlockFormatter}),d=new o({name:"getUncle",call:s,params:3,inputFormatter:[r.toHex,r.toHex,function(t){return!!t}],outputFormatter:n.outputBlockFormatter}),g=new o({name:"getCompilers",call:"eth_getCompilers",params:0}),v=new o({name:"getBlockTransactionCount",call:c,params:1,inputFormatter:[n.inputBlockNumberFormatter],outputFormatter:r.toDecimal}),b=new o({name:"getBlockUncleCount",call:l,params:1,inputFormatter:[n.inputBlockNumberFormatter],outputFormatter:r.toDecimal}),y=new o({name:"getTransaction",call:"eth_getTransactionByHash",params:1,outputFormatter:n.outputTransactionFormatter}),w=new o({name:"getTransactionFromBlock",call:u,params:2,inputFormatter:[r.toHex,r.toHex],outputFormatter:n.outputTransactionFormatter}),x=new o({name:"getTransactionCount",call:"eth_getTransactionCount",params:2,inputFormatter:[null,n.inputDefaultBlockNumberFormatter],outputFormatter:r.toDecimal}),I=new o({name:"sendTransaction",call:"eth_sendTransaction",params:1,inputFormatter:[n.inputTransactionFormatter]}),F=new o({name:"call",call:"eth_call",params:2,inputFormatter:[n.inputTransactionFormatter,n.inputDefaultBlockNumberFormatter]}),_=new o({name:"compile.solidity",call:"eth_compileSolidity",params:1}),T=new o({name:"compile.lll",call:"eth_compileLLL",params:1}),N=new o({name:"compile.serpent",call:"eth_compileSerpent",params:1}),O=new o({name:"flush",call:"eth_flush",params:0}),B=[f,p,m,h,d,g,v,b,y,w,x,F,I,_,T,N,O],D=[new i({name:"coinbase",getter:"eth_coinbase"}),new i({name:"mining",getter:"eth_mining"}),new i({name:"gasPrice",getter:"eth_gasPrice",outputFormatter:n.inputNumberFormatter}),new i({name:"accounts",getter:"eth_accounts"}),new i({name:"blockNumber",getter:"eth_blockNumber",outputFormatter:r.toDecimal})];e.exports={methods:B,properties:D}},{"../utils/utils":6,"./formatters":15,"./method":18,"./property":20}],13:[function(t,e){var n=t("../solidity/abi"),r=t("../utils/utils"),o=t("./signature"),i=function(t,e){return t.filter(function(t){return t.indexed===e})},a=function(t,e){var n=r.findIndex(t,function(t){return t.name===e});return-1===n?void console.error("indexed param with name "+e+" not found"):t[n]},u=function(t,e){return Object.keys(e).map(function(r){var o=[a(i(t.inputs,!0),r)],u=e[r];return u instanceof Array?u.map(function(t){return n.formatInput(o,[t])}):"0x"+n.formatInput(o,[u])})},s=function(t,e,n){return function(r,o){var i=o||{};return i.address=t,i.topics=[],i.topics.push(e),r&&(i.topics=i.topics.concat(u(n,r))),i}},c=function(t,e,n){var r=e.slice(),o=n.slice();return t.reduce(function(t,e){var n;return n=e.indexed?r.splice(0,1)[0]:o.splice(0,1)[0],t[e.name]=n,t},{})},l=function(t){return function(e){var o={event:r.extractDisplayName(t.name),number:e.number,hash:e.hash,args:{}};if(!e.topics)return o;e.data=e.data||"";var a=i(t.inputs,!0),u="0x"+e.topics.slice(1,e.topics.length).map(function(t){return t.slice(2)}).join(""),s=n.formatOutput(a,u),l=i(t.inputs,!1),f=n.formatOutput(l,e.data);return o.args=c(t.inputs,s,f),o}},f=function(t,e){for(var n=0;n<t.length;n++){var r=o.eventSignatureFromAscii(t[n].name);if(r===e.topics[0])return t[n]}return void 0};e.exports={inputParser:s,outputParser:l,getMatchingEvent:f}},{"../solidity/abi":1,"../utils/utils":6,"./signature":24}],14:[function(t,e){var n=t("./requestmanager"),r=t("./formatters"),o=t("../utils/utils"),i=function(t){return o.isString(t)?t:(t=t||{},t.topics=t.topics||[],t.topics=t.topics.map(function(t){return o.toHex(t)}),{topics:t.topics,to:t.to,address:t.address,fromBlock:r.inputBlockNumberFormatter(t.fromBlock),toBlock:r.inputBlockNumberFormatter(t.toBlock)})},a=function(t,e,n){var r={};e.forEach(function(t){t.attachToObject(r)}),this.options=i(t),this.implementation=r,this.callbacks=[],this.formatter=n,this.filterId=this.implementation.newFilter(this.options)};a.prototype.watch=function(t){this.callbacks.push(t);var e=this,r=function(t,n){return t?e.callbacks.forEach(function(e){e(t)}):void n.forEach(function(t){t=e.formatter?e.formatter(t):t,e.callbacks.forEach(function(e){e(null,t)})})};n.getInstance().startPolling({method:this.implementation.poll.call,params:[this.filterId]},this.filterId,r,this.stopWatching.bind(this))},a.prototype.stopWatching=function(){n.getInstance().stopPolling(this.filterId),this.implementation.uninstallFilter(this.filterId),this.callbacks=[]},a.prototype.get=function(){var t=this.implementation.getLogs(this.filterId),e=this;return t.map(function(t){return e.formatter?e.formatter(t):t})},e.exports=a},{"../utils/utils":6,"./formatters":15,"./requestmanager":22}],15:[function(t,e){var n=t("../utils/utils"),r=t("../utils/config"),o=function(t){return n.toBigNumber(t)},i=function(t){return"latest"===t||"pending"===t||"earliest"===t},a=function(t){return void 0===t?r.ETH_DEFAULTBLOCK:u(t)},u=function(t){return void 0===t?void 0:i(t)?t:n.toHex(t)},s=function(t){return t.code&&(t.data=t.code,delete t.code),["gasPrice","gas","value"].filter(function(e){return void 0!==t[e]}).forEach(function(e){t[e]=n.fromDecimal(t[e])}),t},c=function(t){return t.blockNumber=n.toDecimal(t.blockNumber),t.transactionIndex=n.toDecimal(t.transactionIndex),t.gas=n.toDecimal(t.gas),t.gasPrice=n.toBigNumber(t.gasPrice),t.value=n.toBigNumber(t.value),t},l=function(t){return t.gasLimit=n.toDecimal(t.gasLimit),t.gasUsed=n.toDecimal(t.gasUsed),t.size=n.toDecimal(t.size),t.timestamp=n.toDecimal(t.timestamp),t.number=n.toDecimal(t.number),t.minGasPrice=n.toBigNumber(t.minGasPrice),t.difficulty=n.toBigNumber(t.difficulty),t.totalDifficulty=n.toBigNumber(t.totalDifficulty),n.isArray(t.transactions)&&t.transactions.forEach(function(t){return n.isString(t)?void 0:c(t)}),t},f=function(t){return null===t?null:(t.blockNumber=n.toDecimal(t.blockNumber),t.transactionIndex=n.toDecimal(t.transactionIndex),t.logIndex=n.toDecimal(t.logIndex),t)},p=function(t){return t.payload=n.toHex(t.payload),t.ttl=n.fromDecimal(t.ttl),t.priority=n.fromDecimal(t.priority),n.isArray(t.topics)||(t.topics=[t.topics]),t.topics=t.topics.map(function(t){return n.fromAscii(t)}),t},m=function(t){return t.expiry=n.toDecimal(t.expiry),t.sent=n.toDecimal(t.sent),t.ttl=n.toDecimal(t.ttl),t.workProved=n.toDecimal(t.workProved),t.payloadRaw=t.payload,t.payload=n.toAscii(t.payload),n.isJson(t.payload)&&(t.payload=JSON.parse(t.payload)),t.topics=t.topics.map(function(t){return n.toAscii(t)}),t};e.exports={inputDefaultBlockNumberFormatter:a,inputBlockNumberFormatter:u,inputTransactionFormatter:s,inputPostFormatter:p,outputBigNumberFormatter:o,outputTransactionFormatter:c,outputBlockFormatter:l,outputLogFormatter:f,outputPostFormatter:m}},{"../utils/config":5,"../utils/utils":6}],16:[function(t,e){"use strict";var n=t("xmlhttprequest").XMLHttpRequest,r=function(t){this.host=t||"http://localhost:8080"};r.prototype.send=function(t){var e=new n;return e.open("POST",this.host,!1),e.send(JSON.stringify(t)),JSON.parse(e.responseText)},r.prototype.sendAsync=function(t,e){var r=new n;r.onreadystatechange=function(){4===r.readyState&&e(null,JSON.parse(r.responseText))},r.open("POST",this.host,!0),r.send(JSON.stringify(t))},e.exports=r},{xmlhttprequest:4}],17:[function(t,e){var n=function(){return arguments.callee._singletonInstance?arguments.callee._singletonInstance:(arguments.callee._singletonInstance=this,void(this.messageId=1))};n.getInstance=function(){var t=new n;return t},n.prototype.toPayload=function(t,e){return t||console.error("jsonrpc method should be specified!"),{jsonrpc:"2.0",method:t,params:e||[],id:this.messageId++}},n.prototype.isValidResponse=function(t){return!!t&&!t.error&&"2.0"===t.jsonrpc&&"number"==typeof t.id&&void 0!==t.result},n.prototype.toBatchPayload=function(t){var e=this;return t.map(function(t){return e.toPayload(t.method,t.params)})},e.exports=n},{}],18:[function(t,e){var n=t("./requestmanager"),r=t("../utils/utils"),o=t("./errors"),i=function(t){this.name=t.name,this.call=t.call,this.params=t.params||0,this.inputFormatter=t.inputFormatter,this.outputFormatter=t.outputFormatter};i.prototype.getCall=function(t){return r.isFunction(this.call)?this.call(t):this.call},i.prototype.extractCallback=function(t){return r.isFunction(t[t.length-1])?t.pop():null},i.prototype.validateArgs=function(t){if(t.length!==this.params)throw o.InvalidNumberOfParams},i.prototype.formatInput=function(t){return this.inputFormatter?this.inputFormatter.map(function(e,n){return e?e(t[n]):t[n]}):t},i.prototype.formatOutput=function(t){return this.outputFormatter&&null!==t?this.outputFormatter(t):t},i.prototype.attachToObject=function(t){var e=this.send.bind(this);e.call=this.call;var n=this.name.split(".");n.length>1?(t[n[0]]=t[n[0]]||{},t[n[0]][n[1]]=e):t[n[0]]=e},i.prototype.toPayload=function(t){var e=this.getCall(t),n=this.extractCallback(t),r=this.formatInput(t);return this.validateArgs(r),{method:e,params:r,callback:n}},i.prototype.send=function(){var t=this.toPayload(Array.prototype.slice.call(arguments));if(t.callback){var e=this;return n.getInstance().sendAsync(t,function(n,r){t.callback(null,e.formatOutput(r))})}return this.formatOutput(n.getInstance().send(t))},e.exports=i},{"../utils/utils":6,"./errors":11,"./requestmanager":22}],19:[function(t,e){var n=t("../utils/utils"),r=t("./property"),o=[],i=[new r({name:"listening",getter:"net_listening"}),new r({name:"peerCount",getter:"net_peerCount",outputFormatter:n.toDecimal})];e.exports={methods:o,properties:i}},{"../utils/utils":6,"./property":20}],20:[function(t,e){var n=t("./requestmanager"),r=function(t){this.name=t.name,this.getter=t.getter,this.setter=t.setter,this.outputFormatter=t.outputFormatter,this.inputFormatter=t.inputFormatter};r.prototype.formatInput=function(t){return this.inputFormatter?this.inputFormatter(t):t},r.prototype.formatOutput=function(t){return this.outputFormatter&&null!==t?this.outputFormatter(t):t},r.prototype.attachToObject=function(t){var e={get:this.get.bind(this),set:this.set.bind(this)},n=this.name.split(".");n.length>1?(t[n[0]]=t[n[0]]||{},Object.defineProperty(t[n[0]],n[1],e)):Object.defineProperty(t,n[0],e)},r.prototype.get=function(){return this.formatOutput(n.getInstance().send({method:this.getter}))},r.prototype.set=function(t){return n.getInstance().send({method:this.setter,params:[this.formatInput(t)]})},e.exports=r},{"./requestmanager":22}],21:[function(t,e){var n=function(){};n.prototype.send=function(t){var e=navigator.qt.callMethod(JSON.stringify(t));return JSON.parse(e)},e.exports=n},{}],22:[function(t,e){var n=t("./jsonrpc"),r=t("../utils/utils"),o=t("../utils/config"),i=t("./errors"),a=function(t){return arguments.callee._singletonInstance?arguments.callee._singletonInstance:(arguments.callee._singletonInstance=this,this.provider=t,this.polls=[],this.timeout=null,void this.poll())};a.getInstance=function(){var t=new a;return t},a.prototype.send=function(t){if(!this.provider)return console.error(i.InvalidProvider),null;var e=n.getInstance().toPayload(t.method,t.params),r=this.provider.send(e);if(!n.getInstance().isValidResponse(r))throw i.InvalidResponse(r);return r.result},a.prototype.sendAsync=function(t,e){if(!this.provider)return e(i.InvalidProvider);var r=n.getInstance().toPayload(t.method,t.params);this.provider.sendAsync(r,function(t,r){return t?e(t):n.getInstance().isValidResponse(r)?void e(null,r.result):e(i.InvalidResponse(r))})},a.prototype.setProvider=function(t){this.provider=t},a.prototype.startPolling=function(t,e,n,r){this.polls.push({data:t,id:e,callback:n,uninstall:r})},a.prototype.stopPolling=function(t){for(var e=this.polls.length;e--;){var n=this.polls[e];n.id===t&&this.polls.splice(e,1)}},a.prototype.reset=function(){this.polls.forEach(function(t){t.uninstall(t.id)}),this.polls=[],this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.poll()},a.prototype.poll=function(){if(this.timeout=setTimeout(this.poll.bind(this),o.ETH_POLLING_TIMEOUT),this.polls.length){if(!this.provider)return void console.error(i.InvalidProvider);var t=n.getInstance().toBatchPayload(this.polls.map(function(t){return t.data})),e=this;this.provider.sendAsync(t,function(t,o){if(!t){if(!r.isArray(o))throw i.InvalidResponse(o);o.map(function(t,n){return t.callback=e.polls[n].callback,t}).filter(function(t){var e=n.getInstance().isValidResponse(t);return e||t.callback(i.InvalidResponse(t)),e}).filter(function(t){return r.isArray(t.result)&&t.result.length>0}).forEach(function(t){t.callback(null,t.result)})}})}},e.exports=a},{"../utils/config":5,"../utils/utils":6,"./errors":11,"./jsonrpc":17}],23:[function(t,e){var n=t("./method"),r=t("./formatters"),o=new n({name:"post",call:"shh_post",params:1,inputFormatter:r.inputPostFormatter}),i=new n({name:"newIdentity",call:"shh_newIdentity",params:0}),a=new n({name:"hasIdentity",call:"shh_hasIdentity",params:1}),u=new n({name:"newGroup",call:"shh_newGroup",params:0}),s=new n({name:"addToGroup",call:"shh_addToGroup",params:0}),c=[o,i,a,u,s];e.exports={methods:c}},{"./formatters":15,"./method":18}],24:[function(t,e){var n=t("../web3"),r=t("../utils/config"),o=function(t){return n.sha3(n.fromAscii(t)).slice(0,2+2*r.ETH_SIGNATURE_LENGTH)},i=function(t){return n.sha3(n.fromAscii(t))};e.exports={functionSignatureFromAscii:o,eventSignatureFromAscii:i}},{"../utils/config":5,"../web3":8}],25:[function(t,e){var n=t("./method"),r=function(){var t=function(t){return"string"==typeof t[0]?"eth_newBlockFilter":"eth_newFilter"},e=new n({name:"newFilter",call:t,params:1}),r=new n({name:"uninstallFilter",call:"eth_uninstallFilter",params:1}),o=new n({name:"getLogs",call:"eth_getFilterLogs",params:1}),i=new n({name:"poll",call:"eth_getFilterChanges",params:1});return[e,r,o,i]},o=function(){var t=new n({name:"newFilter",call:"shh_newFilter",params:1}),e=new n({name:"uninstallFilter",call:"shh_uninstallFilter",params:1}),r=new n({name:"getLogs",call:"shh_getMessages",params:1}),o=new n({name:"poll",call:"shh_getFilterChanges",params:1});return[t,e,r,o]};e.exports={eth:r,shh:o}},{"./method":18}],26:[function(){},{}],"bignumber.js":[function(t,e){"use strict";e.exports=BigNumber},{}],"ethereum.js":[function(t,e){var n=t("./lib/web3");n.providers.HttpProvider=t("./lib/web3/httpprovider"),n.providers.QtSyncProvider=t("./lib/web3/qtsync"),n.eth.contract=t("./lib/web3/contract"),n.abi=t("./lib/solidity/abi"),e.exports=n},{"./lib/solidity/abi":1,"./lib/web3":8,"./lib/web3/contract":9,"./lib/web3/httpprovider":16,"./lib/web3/qtsync":21}]},{},["ethereum.js"]);`
diff --git a/jsre/pp_js.go b/jsre/pp_js.go
index 2badb90e7..5c09b2586 100644
--- a/jsre/pp_js.go
+++ b/jsre/pp_js.go
@@ -2,17 +2,13 @@ package jsre
const pp_js = `
function pp(object, indent) {
- var str = "";
- /*
- var o = object;
try {
- object = JSON.stringify(object)
- object = JSON.parse(object);
- } catch(e) {
- object = o;
- }
- */
+ JSON.stringify(object)
+ } catch(e) {
+ return pp(e, indent);
+ }
+ var str = "";
if(object instanceof Array) {
str += "[";
for(var i = 0, l = object.length; i < l; i++) {
@@ -24,7 +20,7 @@ function pp(object, indent) {
}
str += " ]";
} else if (object instanceof Error) {
- str += "\033[31m" + "Error";
+ str += "\033[31m" + "Error:\033[0m " + object.message;
} else if (isBigNumber(object)) {
str += "\033[32m'" + object.toString(10) + "'";
} else if(typeof(object) === "object") {
diff --git a/logger/glog/glog.go b/logger/glog/glog.go
index a0c4727f8..008c0e036 100644
--- a/logger/glog/glog.go
+++ b/logger/glog/glog.go
@@ -128,6 +128,10 @@ func GetTraceLocation() *TraceLocation {
return &logging.traceLocation
}
+func GetVModule() *moduleSpec {
+ return &logging.vmodule
+}
+
// get returns the value of the severity.
func (s *severity) get() severity {
return severity(atomic.LoadInt32((*int32)(s)))
diff --git a/logger/glog/glog_file.go b/logger/glog/glog_file.go
index 847e9b07c..2fc96eb4e 100644
--- a/logger/glog/glog_file.go
+++ b/logger/glog/glog_file.go
@@ -40,6 +40,10 @@ var logDirs []string
//var logDir = flag.String("log_dir", "", "If non-empty, write log files in this directory")
var logDir *string = new(string)
+func SetLogDir(str string) {
+ *logDir = str
+}
+
func createLogDirs() {
if *logDir != "" {
logDirs = append(logDirs, *logDir)
diff --git a/miner/miner.go b/miner/miner.go
index 23e48db40..aa6c059ba 100644
--- a/miner/miner.go
+++ b/miner/miner.go
@@ -6,6 +6,8 @@ import (
"github.com/ethereum/ethash"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core"
+ "github.com/ethereum/go-ethereum/core/state"
+ "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/pow"
)
@@ -26,6 +28,7 @@ func New(eth core.Backend, pow pow.PoW, minerThreads int) *Miner {
for i := 0; i < minerThreads; i++ {
miner.worker.register(NewCpuMiner(i, pow))
}
+
return miner
}
@@ -40,6 +43,7 @@ func (self *Miner) Start(coinbase common.Address) {
self.pow.(*ethash.Ethash).UpdateDAG()
self.worker.start()
+
self.worker.commitNewWork()
}
@@ -61,3 +65,11 @@ func (self *Miner) HashRate() int64 {
func (self *Miner) SetExtra(extra []byte) {
self.worker.extra = extra
}
+
+func (self *Miner) PendingState() *state.StateDB {
+ return self.worker.pendingState()
+}
+
+func (self *Miner) PendingBlock() *types.Block {
+ return self.worker.pendingBlock()
+}
diff --git a/miner/worker.go b/miner/worker.go
index da10cf7cd..8613df1c0 100644
--- a/miner/worker.go
+++ b/miner/worker.go
@@ -76,16 +76,20 @@ type worker struct {
coinbase common.Address
extra []byte
- current *environment
+ currentMu sync.Mutex
+ current *environment
uncleMu sync.Mutex
possibleUncles map[common.Hash]*types.Block
- mining bool
+ txQueueMu sync.Mutex
+ txQueue map[common.Hash]*types.Transaction
+
+ mining int64
}
func newWorker(coinbase common.Address, eth core.Backend) *worker {
- return &worker{
+ worker := &worker{
eth: eth,
mux: eth.EventMux(),
recv: make(chan *types.Block),
@@ -93,28 +97,45 @@ func newWorker(coinbase common.Address, eth core.Backend) *worker {
proc: eth.BlockProcessor(),
possibleUncles: make(map[common.Hash]*types.Block),
coinbase: coinbase,
+ txQueue: make(map[common.Hash]*types.Transaction),
}
+ go worker.update()
+ go worker.wait()
+
+ worker.quit = make(chan struct{})
+
+ worker.commitNewWork()
+
+ return worker
}
-func (self *worker) start() {
- self.mining = true
+func (self *worker) pendingState() *state.StateDB {
+ self.currentMu.Lock()
+ defer self.currentMu.Unlock()
+
+ return self.current.state
+}
+
+func (self *worker) pendingBlock() *types.Block {
+ self.currentMu.Lock()
+ defer self.currentMu.Unlock()
- self.quit = make(chan struct{})
+ return self.current.block
+}
+func (self *worker) start() {
// spin up agents
for _, agent := range self.agents {
agent.Start()
}
- go self.update()
- go self.wait()
+ atomic.StoreInt64(&self.mining, 1)
}
func (self *worker) stop() {
- self.mining = false
- atomic.StoreInt64(&self.atWork, 0)
+ atomic.StoreInt64(&self.mining, 0)
- close(self.quit)
+ atomic.StoreInt64(&self.atWork, 0)
}
func (self *worker) register(agent Agent) {
@@ -123,7 +144,7 @@ func (self *worker) register(agent Agent) {
}
func (self *worker) update() {
- events := self.mux.Subscribe(core.ChainHeadEvent{}, core.ChainSideEvent{})
+ events := self.mux.Subscribe(core.ChainHeadEvent{}, core.ChainSideEvent{}, core.TxPreEvent{})
timer := time.NewTicker(2 * time.Second)
@@ -138,6 +159,10 @@ out:
self.uncleMu.Lock()
self.possibleUncles[ev.Block.Hash()] = ev.Block
self.uncleMu.Unlock()
+ case core.TxPreEvent:
+ if atomic.LoadInt64(&self.mining) == 0 {
+ self.commitNewWork()
+ }
}
case <-self.quit:
@@ -152,7 +177,7 @@ out:
}
// XXX In case all mined a possible uncle
- if atomic.LoadInt64(&self.atWork) == 0 {
+ if atomic.LoadInt64(&self.atWork) == 0 && atomic.LoadInt64(&self.mining) == 1 {
self.commitNewWork()
}
}
@@ -192,7 +217,7 @@ func (self *worker) wait() {
}
func (self *worker) push() {
- if self.mining {
+ if atomic.LoadInt64(&self.mining) == 1 {
self.current.block.Header().GasUsed = self.current.totalUsedGas
self.current.block.SetRoot(self.current.state.Root())
@@ -205,12 +230,7 @@ func (self *worker) push() {
}
}
-func (self *worker) commitNewWork() {
- self.mu.Lock()
- defer self.mu.Unlock()
- self.uncleMu.Lock()
- defer self.uncleMu.Unlock()
-
+func (self *worker) makeCurrent() {
block := self.chain.NewBlock(self.coinbase)
if block.Time() == self.chain.CurrentBlock().Time() {
block.Header().Time++
@@ -224,6 +244,17 @@ func (self *worker) commitNewWork() {
parent := self.chain.GetBlock(self.current.block.ParentHash())
self.current.coinbase.SetGasPool(core.CalcGasLimit(parent, self.current.block))
+}
+
+func (self *worker) commitNewWork() {
+ self.mu.Lock()
+ defer self.mu.Unlock()
+ self.uncleMu.Lock()
+ defer self.uncleMu.Unlock()
+ self.currentMu.Lock()
+ defer self.currentMu.Unlock()
+
+ self.makeCurrent()
transactions := self.eth.TxPool().GetTransactions()
sort.Sort(types.TxByNonce{transactions})
@@ -245,12 +276,12 @@ gasLimit:
self.chain.TxState().RemoveNonce(from, tx.Nonce())
remove = append(remove, tx)
- if glog.V(logger.Info) {
+ if glog.V(logger.Debug) {
glog.Infof("TX (%x) failed, will be removed: %v\n", tx.Hash().Bytes()[:4], err)
+ glog.Infoln(tx)
}
- glog.V(logger.Debug).Infoln(tx)
case state.IsGasLimitErr(err):
- glog.V(logger.Info).Infof("Gas limit reached for block. %d TXs included in this block\n", i)
+ glog.V(logger.Debug).Infof("Gas limit reached for block. %d TXs included in this block\n", i)
// Break on gas limit
break gasLimit
default:
@@ -269,15 +300,20 @@ gasLimit:
}
if err := self.commitUncle(uncle.Header()); err != nil {
- glog.V(logger.Info).Infof("Bad uncle found and will be removed (%x)\n", hash[:4])
+ glog.V(logger.Debug).Infof("Bad uncle found and will be removed (%x)\n", hash[:4])
glog.V(logger.Debug).Infoln(uncle)
badUncles = append(badUncles, hash)
} else {
- glog.V(logger.Info).Infof("commiting %x as uncle\n", hash[:4])
+ glog.V(logger.Debug).Infof("commiting %x as uncle\n", hash[:4])
uncles = append(uncles, uncle.Header())
}
}
- glog.V(logger.Info).Infof("commit new work on block %v with %d txs & %d uncles\n", self.current.block.Number(), tcount, len(uncles))
+
+ // We only care about logging if we're actually mining
+ if atomic.LoadInt64(&self.mining) == 1 {
+ glog.V(logger.Info).Infof("commit new work on block %v with %d txs & %d uncles\n", self.current.block.Number(), tcount, len(uncles))
+ }
+
for _, hash := range badUncles {
delete(self.possibleUncles, hash)
}
@@ -287,6 +323,7 @@ gasLimit:
core.AccumulateRewards(self.current.state, self.current.block)
self.current.state.Update()
+
self.push()
}
diff --git a/p2p/discover/udp.go b/p2p/discover/udp.go
index e9ede1397..a638a8f35 100644
--- a/p2p/discover/udp.go
+++ b/p2p/discover/udp.go
@@ -10,12 +10,11 @@ import (
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/logger"
+ "github.com/ethereum/go-ethereum/logger/glog"
"github.com/ethereum/go-ethereum/p2p/nat"
"github.com/ethereum/go-ethereum/rlp"
)
-var log = logger.NewLogger("P2P Discovery")
-
const Version = 3
// Errors
@@ -155,7 +154,7 @@ func ListenUDP(priv *ecdsa.PrivateKey, laddr string, natm nat.Interface) (*Table
return nil, err
}
tab, _ := newUDP(priv, conn, natm)
- log.Infoln("Listening,", tab.self)
+ glog.V(logger.Info).Infoln("Listening,", tab.self)
return tab, nil
}
@@ -336,9 +335,9 @@ func (t *udp) send(toaddr *net.UDPAddr, ptype byte, req interface{}) error {
if err != nil {
return err
}
- log.DebugDetailf(">>> %v %T %v\n", toaddr, req, req)
+ glog.V(logger.Detail).Infof(">>> %v %T %v\n", toaddr, req, req)
if _, err = t.conn.WriteToUDP(packet, toaddr); err != nil {
- log.DebugDetailln("UDP send failed:", err)
+ glog.V(logger.Detail).Infoln("UDP send failed:", err)
}
return err
}
@@ -348,13 +347,13 @@ func encodePacket(priv *ecdsa.PrivateKey, ptype byte, req interface{}) ([]byte,
b.Write(headSpace)
b.WriteByte(ptype)
if err := rlp.Encode(b, req); err != nil {
- log.Errorln("error encoding packet:", err)
+ glog.V(logger.Error).Infoln("error encoding packet:", err)
return nil, err
}
packet := b.Bytes()
sig, err := crypto.Sign(crypto.Sha3(packet[headSize:]), priv)
if err != nil {
- log.Errorln("could not sign packet:", err)
+ glog.V(logger.Error).Infoln("could not sign packet:", err)
return nil, err
}
copy(packet[macSize:], sig)
@@ -376,13 +375,13 @@ func (t *udp) readLoop() {
}
packet, fromID, hash, err := decodePacket(buf[:nbytes])
if err != nil {
- log.Debugf("Bad packet from %v: %v\n", from, err)
+ glog.V(logger.Debug).Infof("Bad packet from %v: %v\n", from, err)
continue
}
- log.DebugDetailf("<<< %v %T %v\n", from, packet, packet)
+ glog.V(logger.Detail).Infof("<<< %v %T %v\n", from, packet, packet)
go func() {
if err := packet.handle(t, from, fromID, hash); err != nil {
- log.Debugf("error handling %T from %v: %v", packet, from, err)
+ glog.V(logger.Debug).Infof("error handling %T from %v: %v", packet, from, err)
}
}()
}
diff --git a/p2p/nat/nat.go b/p2p/nat/nat.go
index 12d355ba1..4ae7e6b17 100644
--- a/p2p/nat/nat.go
+++ b/p2p/nat/nat.go
@@ -10,11 +10,10 @@ import (
"time"
"github.com/ethereum/go-ethereum/logger"
+ "github.com/ethereum/go-ethereum/logger/glog"
"github.com/jackpal/go-nat-pmp"
)
-var log = logger.NewLogger("P2P NAT")
-
// An implementation of nat.Interface can map local ports to ports
// accessible from the Internet.
type Interface interface {
@@ -87,12 +86,12 @@ func Map(m Interface, c chan struct{}, protocol string, extport, intport int, na
refresh := time.NewTimer(mapUpdateInterval)
defer func() {
refresh.Stop()
- log.Debugf("Deleting port mapping: %s %d -> %d (%s) using %s\n", protocol, extport, intport, name, m)
+ glog.V(logger.Debug).Infof("Deleting port mapping: %s %d -> %d (%s) using %s\n", protocol, extport, intport, name, m)
m.DeleteMapping(protocol, extport, intport)
}()
- log.Debugf("add mapping: %s %d -> %d (%s) using %s\n", protocol, extport, intport, name, m)
+ glog.V(logger.Debug).Infof("add mapping: %s %d -> %d (%s) using %s\n", protocol, extport, intport, name, m)
if err := m.AddMapping(protocol, intport, extport, name, mapTimeout); err != nil {
- log.Errorf("mapping error: %v\n", err)
+ glog.V(logger.Error).Infof("mapping error: %v\n", err)
}
for {
select {
@@ -101,9 +100,9 @@ func Map(m Interface, c chan struct{}, protocol string, extport, intport int, na
return
}
case <-refresh.C:
- log.DebugDetailf("refresh mapping: %s %d -> %d (%s) using %s\n", protocol, extport, intport, name, m)
+ glog.V(logger.Detail).Infof("refresh mapping: %s %d -> %d (%s) using %s\n", protocol, extport, intport, name, m)
if err := m.AddMapping(protocol, intport, extport, name, mapTimeout); err != nil {
- log.Errorf("mapping error: %v\n", err)
+ glog.V(logger.Error).Infof("mapping error: %v\n", err)
}
refresh.Reset(mapUpdateInterval)
}
diff --git a/p2p/server.go b/p2p/server.go
index 813b0676f..0a2621aa8 100644
--- a/p2p/server.go
+++ b/p2p/server.go
@@ -10,6 +10,7 @@ import (
"time"
"github.com/ethereum/go-ethereum/logger"
+ "github.com/ethereum/go-ethereum/logger/glog"
"github.com/ethereum/go-ethereum/p2p/discover"
"github.com/ethereum/go-ethereum/p2p/nat"
"github.com/ethereum/go-ethereum/rlp"
@@ -29,7 +30,6 @@ const (
frameWriteTimeout = 5 * time.Second
)
-var srvlog = logger.NewLogger("P2P Server")
var srvjslog = logger.NewJsonLogger()
// Server manages all peer connections.
@@ -161,7 +161,7 @@ func (srv *Server) Start() (err error) {
if srv.running {
return errors.New("server already running")
}
- srvlog.Infoln("Starting Server")
+ glog.V(logger.Info).Infoln("Starting Server")
// static fields
if srv.PrivateKey == nil {
@@ -204,7 +204,7 @@ func (srv *Server) Start() (err error) {
go srv.dialLoop()
}
if srv.NoDial && srv.ListenAddr == "" {
- srvlog.Warnln("I will be kind-of useless, neither dialing nor listening.")
+ glog.V(logger.Warn).Infoln("I will be kind-of useless, neither dialing nor listening.")
}
srv.running = true
@@ -242,7 +242,7 @@ func (srv *Server) Stop() {
srv.running = false
srv.lock.Unlock()
- srvlog.Infoln("Stopping Server")
+ glog.V(logger.Info).Infoln("Stopping Server")
srv.ntab.Close()
if srv.listener != nil {
// this unblocks listener Accept
@@ -263,13 +263,13 @@ func (srv *Server) Stop() {
// main loop for adding connections via listening
func (srv *Server) listenLoop() {
defer srv.loopWG.Done()
- srvlog.Infoln("Listening on", srv.listener.Addr())
+ glog.V(logger.Info).Infoln("Listening on", srv.listener.Addr())
for {
conn, err := srv.listener.Accept()
if err != nil {
return
}
- srvlog.Debugf("Accepted conn %v\n", conn.RemoteAddr())
+ glog.V(logger.Debug).Infof("Accepted conn %v\n", conn.RemoteAddr())
srv.peerWG.Add(1)
go srv.startPeer(conn, nil)
}
@@ -328,10 +328,10 @@ func (srv *Server) dialLoop() {
func (srv *Server) dialNode(dest *discover.Node) {
addr := &net.TCPAddr{IP: dest.IP, Port: dest.TCPPort}
- srvlog.Debugf("Dialing %v\n", dest)
+ glog.V(logger.Debug).Infof("Dialing %v\n", dest)
conn, err := srv.Dialer.Dial("tcp", addr.String())
if err != nil {
- srvlog.DebugDetailf("dial error: %v", err)
+ glog.V(logger.Detail).Infof("dial error: %v", err)
return
}
srv.startPeer(conn, dest)
@@ -365,7 +365,7 @@ func (srv *Server) startPeer(fd net.Conn, dest *discover.Node) {
conn, err := srv.setupFunc(fd, srv.PrivateKey, srv.ourHandshake, dest)
if err != nil {
fd.Close()
- srvlog.Debugf("Handshake with %v failed: %v", fd.RemoteAddr(), err)
+ glog.V(logger.Debug).Infof("Handshake with %v failed: %v", fd.RemoteAddr(), err)
return
}
@@ -375,12 +375,12 @@ func (srv *Server) startPeer(fd net.Conn, dest *discover.Node) {
}
p := newPeer(fd, conn, srv.Protocols)
if ok, reason := srv.addPeer(conn.ID, p); !ok {
- srvlog.DebugDetailf("Not adding %v (%v)\n", p, reason)
+ glog.V(logger.Detail).Infof("Not adding %v (%v)\n", p, reason)
p.politeDisconnect(reason)
return
}
- srvlog.Debugf("Added %v\n", p)
+ glog.V(logger.Debug).Infof("Added %v\n", p)
srvjslog.LogJson(&logger.P2PConnected{
RemoteId: fmt.Sprintf("%x", conn.ID[:]),
RemoteAddress: fd.RemoteAddr().String(),
@@ -394,7 +394,7 @@ func (srv *Server) startPeer(fd net.Conn, dest *discover.Node) {
discreason := p.run()
srv.removePeer(p)
- srvlog.Debugf("Removed %v (%v)\n", p, discreason)
+ glog.V(logger.Debug).Infof("Removed %v (%v)\n", p, discreason)
srvjslog.LogJson(&logger.P2PDisconnected{
RemoteId: fmt.Sprintf("%x", conn.ID[:]),
NumConnections: srv.PeerCount(),
diff --git a/rpc/api.go b/rpc/api.go
index 30ba1ddc1..6e2ae2e93 100644
--- a/rpc/api.go
+++ b/rpc/api.go
@@ -53,28 +53,21 @@ func (api *EthereumApi) GetRequestReply(req *RpcRequest, reply *interface{}) err
case "net_listening":
*reply = api.xeth().IsListening()
case "net_peerCount":
- v := api.xeth().PeerCount()
- *reply = common.ToHex(big.NewInt(int64(v)).Bytes())
+ *reply = newHexNum(api.xeth().PeerCount())
case "eth_protocolVersion":
*reply = api.xeth().EthVersion()
case "eth_coinbase":
- // TODO handling of empty coinbase due to lack of accounts
- res := api.xeth().Coinbase()
- if res == "0x" || res == "0x0" {
- *reply = nil
- } else {
- *reply = res
- }
+ *reply = newHexData(api.xeth().Coinbase())
case "eth_mining":
*reply = api.xeth().IsMining()
case "eth_gasPrice":
v := xeth.DefaultGas()
- *reply = common.ToHex(v.Bytes())
+ *reply = newHexData(v.Bytes())
case "eth_accounts":
*reply = api.xeth().Accounts()
case "eth_blockNumber":
v := api.xeth().CurrentBlock().Number()
- *reply = common.ToHex(v.Bytes())
+ *reply = newHexNum(v.Bytes())
case "eth_getBalance":
args := new(GetBalanceArgs)
if err := json.Unmarshal(req.Params, &args); err != nil {
@@ -105,7 +98,7 @@ func (api *EthereumApi) GetRequestReply(req *RpcRequest, reply *interface{}) err
}
count := api.xethAtStateNum(args.BlockNumber).TxCountAt(args.Address)
- *reply = common.ToHex(big.NewInt(int64(count)).Bytes())
+ *reply = newHexNum(big.NewInt(int64(count)).Bytes())
case "eth_getBlockTransactionCountByHash":
args := new(HashArgs)
if err := json.Unmarshal(req.Params, &args); err != nil {
@@ -116,7 +109,7 @@ func (api *EthereumApi) GetRequestReply(req *RpcRequest, reply *interface{}) err
if block == nil {
*reply = nil
} else {
- *reply = common.ToHex(big.NewInt(int64(len(block.Transactions))).Bytes())
+ *reply = newHexNum(big.NewInt(int64(len(block.Transactions))).Bytes())
}
case "eth_getBlockTransactionCountByNumber":
args := new(BlockNumArg)
@@ -125,7 +118,12 @@ func (api *EthereumApi) GetRequestReply(req *RpcRequest, reply *interface{}) err
}
block := NewBlockRes(api.xeth().EthBlockByNumber(args.BlockNumber), false)
- *reply = common.ToHex(big.NewInt(int64(len(block.Transactions))).Bytes())
+ if block == nil {
+ *reply = nil
+ break
+ }
+
+ *reply = newHexNum(big.NewInt(int64(len(block.Transactions))).Bytes())
case "eth_getUncleCountByBlockHash":
args := new(HashArgs)
if err := json.Unmarshal(req.Params, &args); err != nil {
@@ -134,7 +132,12 @@ func (api *EthereumApi) GetRequestReply(req *RpcRequest, reply *interface{}) err
block := api.xeth().EthBlockByHash(args.Hash)
br := NewBlockRes(block, false)
- *reply = common.ToHex(big.NewInt(int64(len(br.Uncles))).Bytes())
+ if br == nil {
+ *reply = nil
+ break
+ }
+
+ *reply = newHexNum(big.NewInt(int64(len(br.Uncles))).Bytes())
case "eth_getUncleCountByBlockNumber":
args := new(BlockNumArg)
if err := json.Unmarshal(req.Params, &args); err != nil {
@@ -143,7 +146,12 @@ func (api *EthereumApi) GetRequestReply(req *RpcRequest, reply *interface{}) err
block := api.xeth().EthBlockByNumber(args.BlockNumber)
br := NewBlockRes(block, false)
- *reply = common.ToHex(big.NewInt(int64(len(br.Uncles))).Bytes())
+ if br == nil {
+ *reply = nil
+ break
+ }
+
+ *reply = newHexNum(big.NewInt(int64(len(br.Uncles))).Bytes())
case "eth_getData", "eth_getCode":
args := new(GetDataArgs)
if err := json.Unmarshal(req.Params, &args); err != nil {
@@ -219,6 +227,7 @@ func (api *EthereumApi) GetRequestReply(req *RpcRequest, reply *interface{}) err
br := NewBlockRes(block, true)
if br == nil {
*reply = nil
+ break
}
if args.Index >= int64(len(br.Transactions)) || args.Index < 0 {
@@ -237,6 +246,7 @@ func (api *EthereumApi) GetRequestReply(req *RpcRequest, reply *interface{}) err
v := NewBlockRes(block, true)
if v == nil {
*reply = nil
+ break
}
if args.Index >= int64(len(v.Transactions)) || args.Index < 0 {
@@ -295,14 +305,13 @@ func (api *EthereumApi) GetRequestReply(req *RpcRequest, reply *interface{}) err
}
id := api.xeth().RegisterFilter(args.Earliest, args.Latest, args.Skip, args.Max, args.Address, args.Topics)
- *reply = common.ToHex(big.NewInt(int64(id)).Bytes())
+ *reply = newHexNum(big.NewInt(int64(id)).Bytes())
case "eth_newBlockFilter":
args := new(FilterStringArgs)
if err := json.Unmarshal(req.Params, &args); err != nil {
return err
}
- id := api.xeth().NewFilterString(args.Word)
- *reply = common.ToHex(big.NewInt(int64(id)).Bytes())
+ *reply = newHexNum(api.xeth().NewFilterString(args.Word))
case "eth_uninstallFilter":
args := new(FilterIdArgs)
if err := json.Unmarshal(req.Params, &args); err != nil {
@@ -384,7 +393,7 @@ func (api *EthereumApi) GetRequestReply(req *RpcRequest, reply *interface{}) err
}
res, _ := api.xeth().DbGet([]byte(args.Database + args.Key))
- *reply = common.ToHex(res)
+ *reply = newHexData(res)
case "shh_version":
*reply = api.xeth().WhisperVersion()
case "shh_post":
@@ -425,7 +434,7 @@ func (api *EthereumApi) GetRequestReply(req *RpcRequest, reply *interface{}) err
opts.To = args.To
opts.Topics = args.Topics
id := api.xeth().NewWhisperFilter(opts)
- *reply = common.ToHex(big.NewInt(int64(id)).Bytes())
+ *reply = newHexNum(big.NewInt(int64(id)).Bytes())
case "shh_uninstallFilter":
args := new(FilterIdArgs)
if err := json.Unmarshal(req.Params, &args); err != nil {
diff --git a/rpc/args.go b/rpc/args.go
index cebabf4ba..5b1c271cc 100644
--- a/rpc/args.go
+++ b/rpc/args.go
@@ -36,6 +36,8 @@ func blockHeight(raw interface{}, number *int64) error {
}
switch str {
+ case "earliest":
+ *number = 0
case "latest":
*number = -1
case "pending":
diff --git a/rpc/args_test.go b/rpc/args_test.go
index b88bab280..050f8e472 100644
--- a/rpc/args_test.go
+++ b/rpc/args_test.go
@@ -8,6 +8,61 @@ import (
"testing"
)
+func TestBlockheightInvalidString(t *testing.T) {
+ v := "foo"
+ var num int64
+
+ str := ExpectInvalidTypeError(blockHeight(v, &num))
+ if len(str) > 0 {
+ t.Error(str)
+ }
+}
+
+func TestBlockheightEarliest(t *testing.T) {
+ v := "earliest"
+ e := int64(0)
+ var num int64
+
+ err := blockHeight(v, &num)
+ if err != nil {
+ t.Error(err)
+ }
+
+ if num != e {
+ t.Errorf("Expected %s but got %s", e, num)
+ }
+}
+
+func TestBlockheightLatest(t *testing.T) {
+ v := "latest"
+ e := int64(-1)
+ var num int64
+
+ err := blockHeight(v, &num)
+ if err != nil {
+ t.Error(err)
+ }
+
+ if num != e {
+ t.Errorf("Expected %s but got %s", e, num)
+ }
+}
+
+func TestBlockheightPending(t *testing.T) {
+ v := "pending"
+ e := int64(-2)
+ var num int64
+
+ err := blockHeight(v, &num)
+ if err != nil {
+ t.Error(err)
+ }
+
+ if num != e {
+ t.Errorf("Expected %s but got %s", e, num)
+ }
+}
+
func ExpectValidationError(err error) string {
var str string
switch err.(type) {
@@ -121,6 +176,26 @@ func TestGetBalanceArgs(t *testing.T) {
}
}
+func TestGetBalanceArgsBlocknumMissing(t *testing.T) {
+ input := `["0x407d73d8a49eeb85d32cf465507dd71d507100c1"]`
+ expected := new(GetBalanceArgs)
+ expected.Address = "0x407d73d8a49eeb85d32cf465507dd71d507100c1"
+ expected.BlockNumber = -1
+
+ args := new(GetBalanceArgs)
+ if err := json.Unmarshal([]byte(input), &args); err != nil {
+ t.Error(err)
+ }
+
+ if args.Address != expected.Address {
+ t.Errorf("Address should be %v but is %v", expected.Address, args.Address)
+ }
+
+ if args.BlockNumber != expected.BlockNumber {
+ t.Errorf("BlockNumber should be %v but is %v", expected.BlockNumber, args.BlockNumber)
+ }
+}
+
func TestGetBalanceArgsLatest(t *testing.T) {
input := `["0x407d73d8a49eeb85d32cf465507dd71d507100c1", "latest"]`
expected := new(GetBalanceArgs)
@@ -231,6 +306,16 @@ func TestGetBlockByHashArgsHashInt(t *testing.T) {
}
}
+func TestGetBlockByHashArgsHashBool(t *testing.T) {
+ input := `[false, true]`
+
+ args := new(GetBlockByHashArgs)
+ str := ExpectInvalidTypeError(json.Unmarshal([]byte(input), &args))
+ if len(str) > 0 {
+ t.Error(str)
+ }
+}
+
func TestGetBlockByNumberArgsBlockNum(t *testing.T) {
input := `[436, false]`
expected := new(GetBlockByNumberArgs)
@@ -850,6 +935,26 @@ func TestGetStorageArgs(t *testing.T) {
}
}
+func TestGetStorageArgsMissingBlocknum(t *testing.T) {
+ input := `["0x407d73d8a49eeb85d32cf465507dd71d507100c1"]`
+ expected := new(GetStorageArgs)
+ expected.Address = "0x407d73d8a49eeb85d32cf465507dd71d507100c1"
+ expected.BlockNumber = -1
+
+ args := new(GetStorageArgs)
+ if err := json.Unmarshal([]byte(input), &args); err != nil {
+ t.Error(err)
+ }
+
+ if expected.Address != args.Address {
+ t.Errorf("Address shoud be %#v but is %#v", expected.Address, args.Address)
+ }
+
+ if expected.BlockNumber != args.BlockNumber {
+ t.Errorf("BlockNumber shoud be %#v but is %#v", expected.BlockNumber, args.BlockNumber)
+ }
+}
+
func TestGetStorageInvalidArgs(t *testing.T) {
input := `{}`
@@ -915,6 +1020,31 @@ func TestGetStorageAtArgs(t *testing.T) {
}
}
+func TestGetStorageAtArgsMissingBlocknum(t *testing.T) {
+ input := `["0x407d73d8a49eeb85d32cf465507dd71d507100c1", "0x0"]`
+ expected := new(GetStorageAtArgs)
+ expected.Address = "0x407d73d8a49eeb85d32cf465507dd71d507100c1"
+ expected.Key = "0x0"
+ expected.BlockNumber = -1
+
+ args := new(GetStorageAtArgs)
+ if err := json.Unmarshal([]byte(input), &args); err != nil {
+ t.Error(err)
+ }
+
+ if expected.Address != args.Address {
+ t.Errorf("Address shoud be %#v but is %#v", expected.Address, args.Address)
+ }
+
+ if expected.Key != args.Key {
+ t.Errorf("Address shoud be %#v but is %#v", expected.Address, args.Address)
+ }
+
+ if expected.BlockNumber != args.BlockNumber {
+ t.Errorf("BlockNumber shoud be %#v but is %#v", expected.BlockNumber, args.BlockNumber)
+ }
+}
+
func TestGetStorageAtEmptyArgs(t *testing.T) {
input := `[]`
@@ -1015,6 +1145,26 @@ func TestGetTxCountAddressNotString(t *testing.T) {
}
}
+func TestGetTxCountBlockheightMissing(t *testing.T) {
+ input := `["0x407d73d8a49eeb85d32cf465507dd71d507100c1"]`
+ expected := new(GetTxCountArgs)
+ expected.Address = "0x407d73d8a49eeb85d32cf465507dd71d507100c1"
+ expected.BlockNumber = -1
+
+ args := new(GetTxCountArgs)
+ if err := json.Unmarshal([]byte(input), &args); err != nil {
+ t.Error(err)
+ }
+
+ if expected.Address != args.Address {
+ t.Errorf("Address shoud be %#v but is %#v", expected.Address, args.Address)
+ }
+
+ if expected.BlockNumber != args.BlockNumber {
+ t.Errorf("BlockNumber shoud be %#v but is %#v", expected.BlockNumber, args.BlockNumber)
+ }
+}
+
func TestGetTxCountBlockheightInvalid(t *testing.T) {
input := `["0x407d73d8a49eeb85d32cf465507dd71d507100c1", {}]`
@@ -1045,6 +1195,26 @@ func TestGetDataArgs(t *testing.T) {
}
}
+func TestGetDataArgsBlocknumMissing(t *testing.T) {
+ input := `["0xd5677cf67b5aa051bb40496e68ad359eb97cfbf8"]`
+ expected := new(GetDataArgs)
+ expected.Address = "0xd5677cf67b5aa051bb40496e68ad359eb97cfbf8"
+ expected.BlockNumber = -1
+
+ args := new(GetDataArgs)
+ if err := json.Unmarshal([]byte(input), &args); err != nil {
+ t.Error(err)
+ }
+
+ if expected.Address != args.Address {
+ t.Errorf("Address shoud be %#v but is %#v", expected.Address, args.Address)
+ }
+
+ if expected.BlockNumber != args.BlockNumber {
+ t.Errorf("BlockNumber shoud be %#v but is %#v", expected.BlockNumber, args.BlockNumber)
+ }
+}
+
func TestGetDataArgsEmpty(t *testing.T) {
input := `[]`
@@ -1995,6 +2165,50 @@ func TestWhisperIdentityArgsInt(t *testing.T) {
}
}
+func TestBlockNumArgs(t *testing.T) {
+ input := `["0x29a"]`
+ expected := new(BlockNumIndexArgs)
+ expected.BlockNumber = 666
+
+ args := new(BlockNumArg)
+ if err := json.Unmarshal([]byte(input), &args); err != nil {
+ t.Error(err)
+ }
+
+ if expected.BlockNumber != args.BlockNumber {
+ t.Errorf("BlockNumber shoud be %#v but is %#v", expected.BlockNumber, args.BlockNumber)
+ }
+}
+
+func TestBlockNumArgsInvalid(t *testing.T) {
+ input := `{}`
+
+ args := new(BlockNumArg)
+ str := ExpectDecodeParamError(json.Unmarshal([]byte(input), &args))
+ if len(str) > 0 {
+ t.Error(str)
+ }
+}
+
+func TestBlockNumArgsEmpty(t *testing.T) {
+ input := `[]`
+
+ args := new(BlockNumArg)
+ str := ExpectInsufficientParamsError(json.Unmarshal([]byte(input), &args))
+ if len(str) > 0 {
+ t.Error(str)
+ }
+}
+func TestBlockNumArgsBool(t *testing.T) {
+ input := `[true]`
+
+ args := new(BlockNumArg)
+ str := ExpectInvalidTypeError(json.Unmarshal([]byte(input), &args))
+ if len(str) > 0 {
+ t.Error(str)
+ }
+}
+
func TestBlockNumIndexArgs(t *testing.T) {
input := `["0x29a", "0x0"]`
expected := new(BlockNumIndexArgs)
diff --git a/rpc/responses_test.go b/rpc/responses_test.go
index 2ec6d9d15..e04a064ce 100644
--- a/rpc/responses_test.go
+++ b/rpc/responses_test.go
@@ -26,13 +26,6 @@ const (
)
func TestNewBlockRes(t *testing.T) {
- parentHash := common.HexToHash("0x01")
- coinbase := common.HexToAddress("0x01")
- root := common.HexToHash("0x01")
- difficulty := common.Big1
- nonce := uint64(1)
- extra := ""
- block := types.NewBlock(parentHash, coinbase, root, difficulty, nonce, extra)
tests := map[string]string{
"number": reNum,
"hash": reHash,
@@ -55,16 +48,8 @@ func TestNewBlockRes(t *testing.T) {
// "uncles": reListHash,
}
- to := common.HexToAddress("0x02")
- amount := big.NewInt(1)
- gasAmount := big.NewInt(1)
- gasPrice := big.NewInt(1)
- data := []byte{1, 2, 3}
- tx := types.NewTransactionMessage(to, amount, gasAmount, gasPrice, data)
-
+ block := makeBlock()
v := NewBlockRes(block, false)
- v.Transactions = make([]*TransactionRes, 1)
- v.Transactions[0] = NewTransactionRes(tx)
j, _ := json.Marshal(v)
for k, re := range tests {
@@ -75,14 +60,7 @@ func TestNewBlockRes(t *testing.T) {
}
}
-func TestNewBlockResWithTrans(t *testing.T) {
- parentHash := common.HexToHash("0x01")
- coinbase := common.HexToAddress("0x01")
- root := common.HexToHash("0x01")
- difficulty := common.Big1
- nonce := uint64(1)
- extra := ""
- block := types.NewBlock(parentHash, coinbase, root, difficulty, nonce, extra)
+func TestNewBlockResTxFull(t *testing.T) {
tests := map[string]string{
"number": reNum,
"hash": reHash,
@@ -101,20 +79,12 @@ func TestNewBlockResWithTrans(t *testing.T) {
// "minGasPrice": "0x",
"gasUsed": reNum,
"timestamp": reNum,
- // "transactions": `[{.*}]`,
+ // "transactions": reListHash,
// "uncles": reListHash,
}
- to := common.HexToAddress("0x02")
- amount := big.NewInt(1)
- gasAmount := big.NewInt(1)
- gasPrice := big.NewInt(1)
- data := []byte{1, 2, 3}
- tx := types.NewTransactionMessage(to, amount, gasAmount, gasPrice, data)
-
+ block := makeBlock()
v := NewBlockRes(block, true)
- v.Transactions = make([]*TransactionRes, 1)
- v.Transactions[0] = NewTransactionRes(tx)
j, _ := json.Marshal(v)
for k, re := range tests {
@@ -125,6 +95,16 @@ func TestNewBlockResWithTrans(t *testing.T) {
}
}
+func TestBlockNil(t *testing.T) {
+ var block *types.Block
+ block = nil
+ u := NewBlockRes(block, false)
+ j, _ := json.Marshal(u)
+ if string(j) != "null" {
+ t.Errorf("Expected null but got %v", string(j))
+ }
+}
+
func TestNewTransactionRes(t *testing.T) {
to := common.HexToAddress("0x02")
amount := big.NewInt(1)
@@ -161,6 +141,55 @@ func TestNewTransactionRes(t *testing.T) {
}
+func TestTransactionNil(t *testing.T) {
+ var tx *types.Transaction
+ tx = nil
+ u := NewTransactionRes(tx)
+ j, _ := json.Marshal(u)
+ if string(j) != "null" {
+ t.Errorf("Expected null but got %v", string(j))
+ }
+}
+
+func TestNewUncleRes(t *testing.T) {
+ header := makeHeader()
+ u := NewUncleRes(header)
+ tests := map[string]string{
+ "number": reNum,
+ "hash": reHash,
+ "parentHash": reHash,
+ "nonce": reData,
+ "sha3Uncles": reHash,
+ "receiptHash": reHash,
+ "transactionsRoot": reHash,
+ "stateRoot": reHash,
+ "miner": reAddress,
+ "difficulty": reNum,
+ "extraData": reData,
+ "gasLimit": reNum,
+ "gasUsed": reNum,
+ "timestamp": reNum,
+ }
+
+ j, _ := json.Marshal(u)
+ for k, re := range tests {
+ match, _ := regexp.MatchString(fmt.Sprintf(`{.*"%s":%s.*}`, k, re), string(j))
+ if !match {
+ t.Error(fmt.Sprintf("`%s` output json does not match format %s. Source %s", k, re, j))
+ }
+ }
+}
+
+func TestUncleNil(t *testing.T) {
+ var header *types.Header
+ header = nil
+ u := NewUncleRes(header)
+ j, _ := json.Marshal(u)
+ if string(j) != "null" {
+ t.Errorf("Expected null but got %v", string(j))
+ }
+}
+
func TestNewLogRes(t *testing.T) {
log := makeStateLog(0)
tests := map[string]string{
@@ -217,3 +246,50 @@ func makeStateLog(num int) state.Log {
log := state.NewLog(address, topics, data, number)
return log
}
+
+func makeHeader() *types.Header {
+ header := &types.Header{
+ ParentHash: common.StringToHash("0x00"),
+ UncleHash: common.StringToHash("0x00"),
+ Coinbase: common.StringToAddress("0x00"),
+ Root: common.StringToHash("0x00"),
+ TxHash: common.StringToHash("0x00"),
+ ReceiptHash: common.StringToHash("0x00"),
+ // Bloom:
+ Difficulty: big.NewInt(88888888),
+ Number: big.NewInt(16),
+ GasLimit: big.NewInt(70000),
+ GasUsed: big.NewInt(25000),
+ Time: 124356789,
+ Extra: nil,
+ MixDigest: common.StringToHash("0x00"),
+ Nonce: [8]byte{0, 1, 2, 3, 4, 5, 6, 7},
+ }
+ return header
+}
+
+func makeBlock() *types.Block {
+ parentHash := common.HexToHash("0x01")
+ coinbase := common.HexToAddress("0x01")
+ root := common.HexToHash("0x01")
+ difficulty := common.Big1
+ nonce := uint64(1)
+ block := types.NewBlock(parentHash, coinbase, root, difficulty, nonce, nil)
+
+ txto := common.HexToAddress("0x02")
+ txamount := big.NewInt(1)
+ txgasAmount := big.NewInt(1)
+ txgasPrice := big.NewInt(1)
+ txdata := []byte{1, 2, 3}
+
+ tx := types.NewTransactionMessage(txto, txamount, txgasAmount, txgasPrice, txdata)
+ txs := make([]*types.Transaction, 1)
+ txs[0] = tx
+ block.SetTransactions(txs)
+
+ uncles := make([]*types.Header, 1)
+ uncles[0] = makeHeader()
+ block.SetUncles(uncles)
+
+ return block
+}
diff --git a/rpc/types.go b/rpc/types.go
index 806c9c8a4..bc9a46ed5 100644
--- a/rpc/types.go
+++ b/rpc/types.go
@@ -43,16 +43,11 @@ func (d *hexdata) MarshalJSON() ([]byte, error) {
return json.Marshal(d.String())
}
-func (d *hexdata) UnmarshalJSON(b []byte) (err error) {
- d.data = common.FromHex(string(b))
- return nil
-}
-
func newHexData(input interface{}) *hexdata {
d := new(hexdata)
if input == nil {
- d.data = nil
+ d.isNil = true
return d
}
switch input := input.(type) {
@@ -105,19 +100,19 @@ func newHexData(input interface{}) *hexdata {
case int16:
d.data = big.NewInt(int64(input)).Bytes()
case uint16:
- buff := make([]byte, 8)
+ buff := make([]byte, 2)
binary.BigEndian.PutUint16(buff, input)
d.data = buff
case int32:
d.data = big.NewInt(int64(input)).Bytes()
case uint32:
- buff := make([]byte, 8)
+ buff := make([]byte, 4)
binary.BigEndian.PutUint32(buff, input)
d.data = buff
case string: // hexstring
d.data = common.Big(input).Bytes()
default:
- d.data = nil
+ d.isNil = true
}
return d
@@ -147,11 +142,6 @@ func (d *hexnum) MarshalJSON() ([]byte, error) {
return json.Marshal(d.String())
}
-func (d *hexnum) UnmarshalJSON(b []byte) (err error) {
- d.data = common.FromHex(string(b))
- return nil
-}
-
func newHexNum(input interface{}) *hexnum {
d := new(hexnum)
diff --git a/rpc/types_test.go b/rpc/types_test.go
index 91f0152dc..9ef7b8d38 100644
--- a/rpc/types_test.go
+++ b/rpc/types_test.go
@@ -1,7 +1,13 @@
package rpc
import (
+ "bytes"
+ "encoding/json"
+ "math/big"
"testing"
+
+ "github.com/ethereum/go-ethereum/common"
+ "github.com/ethereum/go-ethereum/core/types"
)
func TestInvalidTypeError(t *testing.T) {
@@ -48,3 +54,151 @@ func TestValidationError(t *testing.T) {
t.Error(err.Error())
}
}
+
+func TestHexdataMarshalNil(t *testing.T) {
+ hd := newHexData([]byte{})
+ hd.isNil = true
+ v, _ := json.Marshal(hd)
+ if string(v) != "null" {
+ t.Errorf("Expected null, got %s", v)
+ }
+}
+
+func TestHexnumMarshalNil(t *testing.T) {
+ hn := newHexNum([]byte{})
+ hn.isNil = true
+ v, _ := json.Marshal(hn)
+ if string(v) != "null" {
+ t.Errorf("Expected null, got %s", v)
+ }
+}
+
+func TestHexdataNil(t *testing.T) {
+ v := newHexData(nil)
+ if v.isNil != true {
+ t.Errorf("Expected isNil to be true, but is %v", v.isNil)
+ }
+}
+
+func TestHexdataPtrHash(t *testing.T) {
+ in := common.Hash{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31}
+ v := newHexData(&in)
+ if bytes.Compare(in.Bytes(), v.data) != 0 {
+ t.Errorf("Got % x expected % x", in, v.data)
+ }
+}
+
+func TestHexdataPtrHashNil(t *testing.T) {
+ var in *common.Hash
+ in = nil
+ v := newHexData(in)
+ if !v.isNil {
+ t.Errorf("Expect isNil to be true, but is %v", v.isNil)
+ }
+}
+
+func TestHexdataPtrAddress(t *testing.T) {
+ in := common.Address{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19}
+ v := newHexData(&in)
+ if bytes.Compare(in.Bytes(), v.data) != 0 {
+ t.Errorf("Got % x expected % x", in, v.data)
+ }
+}
+
+func TestHexdataPtrAddressNil(t *testing.T) {
+ var in *common.Address
+ in = nil
+ v := newHexData(in)
+ if !v.isNil {
+ t.Errorf("Expect isNil to be true, but is %v", v.isNil)
+ }
+}
+
+func TestHexdataPtrBloom(t *testing.T) {
+ in := types.Bloom{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19}
+ v := newHexData(&in)
+ if bytes.Compare(in.Bytes(), v.data) != 0 {
+ t.Errorf("Got % x expected % x", in, v.data)
+ }
+}
+
+func TestHexdataPtrBloomNil(t *testing.T) {
+ var in *types.Bloom
+ in = nil
+ v := newHexData(in)
+ if !v.isNil {
+ t.Errorf("Expect isNil to be true, but is %v", v.isNil)
+ }
+}
+
+func TestHexdataBigintNil(t *testing.T) {
+ var in *big.Int
+ in = nil
+ v := newHexData(in)
+ if !v.isNil {
+ t.Errorf("Expect isNil to be true, but is %v", v.isNil)
+ }
+}
+
+func TestHexdataUint(t *testing.T) {
+ var in = uint(16)
+ var expected = []byte{0x10}
+ v := newHexData(in)
+ if bytes.Compare(expected, v.data) != 0 {
+ t.Errorf("Expected % x got % x", expected, v.data)
+ }
+}
+
+func TestHexdataInt8(t *testing.T) {
+ var in = int8(16)
+ var expected = []byte{0x10}
+ v := newHexData(in)
+ if bytes.Compare(expected, v.data) != 0 {
+ t.Errorf("Expected % x got % x", expected, v.data)
+ }
+}
+
+func TestHexdataUint8(t *testing.T) {
+ var in = uint8(16)
+ var expected = []byte{0x10}
+ v := newHexData(in)
+ if bytes.Compare(expected, v.data) != 0 {
+ t.Errorf("Expected % x got % x", expected, v.data)
+ }
+}
+
+func TestHexdataInt16(t *testing.T) {
+ var in = int16(16)
+ var expected = []byte{0x10}
+ v := newHexData(in)
+ if bytes.Compare(expected, v.data) != 0 {
+ t.Errorf("Expected % x got % x", expected, v.data)
+ }
+}
+
+func TestHexdataUint16(t *testing.T) {
+ var in = uint16(16)
+ var expected = []byte{0x0, 0x10}
+ v := newHexData(in)
+ if bytes.Compare(expected, v.data) != 0 {
+ t.Errorf("Expected % x got % x", expected, v.data)
+ }
+}
+
+func TestHexdataInt32(t *testing.T) {
+ var in = int32(16)
+ var expected = []byte{0x10}
+ v := newHexData(in)
+ if bytes.Compare(expected, v.data) != 0 {
+ t.Errorf("Expected % x got % x", expected, v.data)
+ }
+}
+
+func TestHexdataUint32(t *testing.T) {
+ var in = uint32(16)
+ var expected = []byte{0x0, 0x0, 0x0, 0x10}
+ v := newHexData(in)
+ if bytes.Compare(expected, v.data) != 0 {
+ t.Errorf("Expected % x got % x", expected, v.data)
+ }
+}
diff --git a/whisper/whisper.go b/whisper/whisper.go
index 709667729..00dcb1932 100644
--- a/whisper/whisper.go
+++ b/whisper/whisper.go
@@ -11,6 +11,7 @@ import (
"github.com/ethereum/go-ethereum/crypto/ecies"
"github.com/ethereum/go-ethereum/event/filter"
"github.com/ethereum/go-ethereum/logger"
+ "github.com/ethereum/go-ethereum/logger/glog"
"github.com/ethereum/go-ethereum/p2p"
"gopkg.in/fatih/set.v0"
)
@@ -29,8 +30,6 @@ type MessageEvent struct {
const DefaultTtl = 50 * time.Second
-var wlogger = logger.NewLogger("SHH")
-
type Whisper struct {
protocol p2p.Protocol
filters *filter.Filters
@@ -70,7 +69,7 @@ func (self *Whisper) Version() uint {
}
func (self *Whisper) Start() {
- wlogger.Infoln("Whisper started")
+ glog.V(logger.Info).Infoln("Whisper started")
go self.update()
}
@@ -195,7 +194,7 @@ func (self *Whisper) add(envelope *Envelope) error {
go self.postEvent(envelope)
}
- wlogger.DebugDetailf("added whisper envelope %x\n", envelope)
+ glog.V(logger.Detail).Infof("added whisper envelope %x\n", envelope)
return nil
}
diff --git a/xeth/xeth.go b/xeth/xeth.go
index 825f26017..b8d9ecb08 100644
--- a/xeth/xeth.go
+++ b/xeth/xeth.go
@@ -136,13 +136,16 @@ func cTopics(t [][]string) [][]common.Hash {
func (self *XEth) RemoteMining() *miner.RemoteAgent { return self.agent }
func (self *XEth) AtStateNum(num int64) *XEth {
- block := self.getBlockByHeight(num)
-
var st *state.StateDB
- if block != nil {
- st = state.New(block.Root(), self.backend.StateDb())
- } else {
- st = self.backend.ChainManager().State()
+ switch num {
+ case -2:
+ st = self.backend.Miner().PendingState().Copy()
+ default:
+ if block := self.getBlockByHeight(num); block != nil {
+ st = state.New(block.Root(), self.backend.StateDb())
+ } else {
+ st = state.New(self.backend.ChainManager().GetBlockByNumber(0).Root(), self.backend.StateDb())
+ }
}
return self.withState(st)
@@ -164,9 +167,16 @@ func (self *XEth) Whisper() *Whisper { return self.whisper }
func (self *XEth) getBlockByHeight(height int64) *types.Block {
var num uint64
- if height < 0 {
- num = self.CurrentBlock().NumberU64() + uint64(-1*height)
- } else {
+ switch height {
+ case -2:
+ return self.backend.Miner().PendingBlock()
+ case -1:
+ return self.CurrentBlock()
+ default:
+ if height < 0 {
+ return nil
+ }
+
num = uint64(height)
}