From b5234413611ce5984292f85a01de1f56c045b490 Mon Sep 17 00:00:00 2001 From: obscuren Date: Mon, 16 Mar 2015 11:27:38 +0100 Subject: Moved ethutil => common --- .../src/github.com/ethereum/ethash/ethash.go | 6 +- accounts/abi/numbers.go | 10 +- accounts/abi/type.go | 10 +- blockpool/blockpool_test.go | 8 +- blockpool/blockpool_util_test.go | 4 +- blockpool/peers.go | 6 +- cmd/disasm/main.go | 4 +- cmd/ethereum/blocktest.go | 4 +- cmd/ethereum/js.go | 6 +- cmd/ethereum/main.go | 6 +- cmd/ethtest/main.go | 32 +- cmd/evm/main.go | 12 +- cmd/mist/bindings.go | 14 +- cmd/mist/gui.go | 20 +- cmd/mist/html_container.go | 8 +- cmd/mist/main.go | 4 +- cmd/mist/qml_container.go | 4 +- cmd/mist/ui_lib.go | 26 +- cmd/utils/cmd.go | 10 +- cmd/utils/flags.go | 8 +- common/.gitignore | 12 + common/.travis.yml | 3 + common/README.md | 139 +++++++ common/big.go | 123 +++++++ common/big_test.go | 73 ++++ common/bytes.go | 234 ++++++++++++ common/bytes_test.go | 193 ++++++++++ common/common.go | 165 +++++++++ common/common_test.go | 89 +++++ common/config.go | 67 ++++ common/db.go | 12 + common/list.go | 81 +++++ common/main_test.go | 9 + common/math/dist.go | 80 ++++ common/math/dist_test.go | 66 ++++ common/natspec/natspec.go | 63 ++++ common/natspec/natspec_js.go | 4 + common/natspec/natspec_test.go | 97 +++++ common/number/int.go | 181 ++++++++++ common/number/uint_test.go | 92 +++++ common/package.go | 123 +++++++ common/path.go | 68 ++++ common/path_test.go | 51 +++ common/rlp.go | 276 ++++++++++++++ common/rlp_test.go | 156 ++++++++ common/size.go | 15 + common/size_test.go | 23 ++ common/types.go | 6 + common/value.go | 401 +++++++++++++++++++++ common/value_test.go | 70 ++++ core/asm.go | 6 +- core/block_processor.go | 12 +- core/chain_makers.go | 30 +- core/chain_manager.go | 36 +- core/genesis.go | 18 +- core/helper_test.go | 6 +- core/manager.go | 6 +- core/state_transition.go | 8 +- core/transaction_pool.go | 6 +- core/transaction_pool_test.go | 6 +- core/types/block.go | 10 +- core/types/bloom9.go | 8 +- core/types/bloom9_test.go | 4 +- core/types/derive_sha.go | 4 +- core/types/receipt.go | 14 +- core/types/transaction.go | 18 +- crypto/crypto.go | 10 +- crypto/crypto_test.go | 4 +- crypto/encrypt_decrypt_test.go | 8 +- crypto/key_store_test.go | 10 +- crypto/keypair.go | 10 +- eth/backend.go | 26 +- eth/peer_util.go | 6 +- eth/protocol.go | 14 +- eth/protocol_test.go | 4 +- ethdb/database.go | 4 +- ethdb/memory_database.go | 8 +- ethutil/.gitignore | 12 - ethutil/.travis.yml | 3 - ethutil/README.md | 139 ------- ethutil/big.go | 123 ------- ethutil/big_test.go | 73 ---- ethutil/bytes.go | 234 ------------ ethutil/bytes_test.go | 193 ---------- ethutil/common.go | 165 --------- ethutil/common_test.go | 89 ----- ethutil/config.go | 67 ---- ethutil/db.go | 12 - ethutil/list.go | 81 ----- ethutil/main_test.go | 9 - ethutil/math/dist.go | 80 ---- ethutil/math/dist_test.go | 66 ---- ethutil/natspec/natspec.go | 63 ---- ethutil/natspec/natspec_js.go | 4 - ethutil/natspec/natspec_test.go | 97 ----- ethutil/number/int.go | 181 ---------- ethutil/number/uint_test.go | 92 ----- ethutil/package.go | 123 ------- ethutil/path.go | 68 ---- ethutil/path_test.go | 51 --- ethutil/rlp.go | 276 -------------- ethutil/rlp_test.go | 156 -------- ethutil/size.go | 15 - ethutil/size_test.go | 23 -- ethutil/value.go | 401 --------------------- ethutil/value_test.go | 70 ---- javascript/types.go | 10 +- logger/log.go | 4 +- miner/worker.go | 10 +- p2p/message.go | 4 +- p2p/server.go | 6 +- pow/dagger/dagger.go | 10 +- pow/dagger/dagger_test.go | 4 +- pow/ezp/pow.go | 6 +- rpc/api.go | 22 +- rpc/args.go | 42 +-- rpc/util.go | 4 +- state/dump.go | 10 +- state/log.go | 8 +- state/managed_state_test.go | 4 +- state/state_object.go | 56 +-- state/state_test.go | 8 +- state/statedb.go | 16 +- tests/blocktest.go | 4 +- tests/helper/common.go | 6 +- tests/helper/vm.go | 32 +- tests/vm/gh_test.go | 36 +- trie/hashnode.go | 4 +- trie/shortnode.go | 4 +- trie/trie.go | 16 +- trie/trie_test.go | 22 +- trie/valuenode.go | 4 +- ui/qt/qwhisper/message.go | 6 +- ui/qt/qwhisper/whisper.go | 20 +- vm/address.go | 16 +- vm/asm.go | 6 +- vm/common.go | 16 +- vm/context.go | 4 +- vm/environment.go | 4 +- vm/vm.go | 110 +++--- whisper/envelope.go | 18 +- xeth/state.go | 8 +- xeth/types.go | 30 +- xeth/whisper.go | 14 +- xeth/xeth.go | 56 +-- 145 files changed, 3551 insertions(+), 3545 deletions(-) create mode 100644 common/.gitignore create mode 100644 common/.travis.yml create mode 100644 common/README.md create mode 100644 common/big.go create mode 100644 common/big_test.go create mode 100644 common/bytes.go create mode 100644 common/bytes_test.go create mode 100644 common/common.go create mode 100644 common/common_test.go create mode 100644 common/config.go create mode 100644 common/db.go create mode 100644 common/list.go create mode 100644 common/main_test.go create mode 100644 common/math/dist.go create mode 100644 common/math/dist_test.go create mode 100644 common/natspec/natspec.go create mode 100644 common/natspec/natspec_js.go create mode 100644 common/natspec/natspec_test.go create mode 100644 common/number/int.go create mode 100644 common/number/uint_test.go create mode 100644 common/package.go create mode 100644 common/path.go create mode 100644 common/path_test.go create mode 100644 common/rlp.go create mode 100644 common/rlp_test.go create mode 100644 common/size.go create mode 100644 common/size_test.go create mode 100644 common/types.go create mode 100644 common/value.go create mode 100644 common/value_test.go delete mode 100644 ethutil/.gitignore delete mode 100644 ethutil/.travis.yml delete mode 100644 ethutil/README.md delete mode 100644 ethutil/big.go delete mode 100644 ethutil/big_test.go delete mode 100644 ethutil/bytes.go delete mode 100644 ethutil/bytes_test.go delete mode 100644 ethutil/common.go delete mode 100644 ethutil/common_test.go delete mode 100644 ethutil/config.go delete mode 100644 ethutil/db.go delete mode 100644 ethutil/list.go delete mode 100644 ethutil/main_test.go delete mode 100644 ethutil/math/dist.go delete mode 100644 ethutil/math/dist_test.go delete mode 100644 ethutil/natspec/natspec.go delete mode 100644 ethutil/natspec/natspec_js.go delete mode 100644 ethutil/natspec/natspec_test.go delete mode 100644 ethutil/number/int.go delete mode 100644 ethutil/number/uint_test.go delete mode 100644 ethutil/package.go delete mode 100644 ethutil/path.go delete mode 100644 ethutil/path_test.go delete mode 100644 ethutil/rlp.go delete mode 100644 ethutil/rlp_test.go delete mode 100644 ethutil/size.go delete mode 100644 ethutil/size_test.go delete mode 100644 ethutil/value.go delete mode 100644 ethutil/value_test.go diff --git a/Godeps/_workspace/src/github.com/ethereum/ethash/ethash.go b/Godeps/_workspace/src/github.com/ethereum/ethash/ethash.go index 1f615058d..7328bc922 100644 --- a/Godeps/_workspace/src/github.com/ethereum/ethash/ethash.go +++ b/Godeps/_workspace/src/github.com/ethereum/ethash/ethash.go @@ -32,7 +32,7 @@ import ( "unsafe" "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/pow" ) @@ -337,7 +337,7 @@ 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 := ethutil.Bytes2Big(C.GoBytes(unsafe.Pointer(&ret.result[0]), C.int(32))) + result := common.Bytes2Big(C.GoBytes(unsafe.Pointer(&ret.result[0]), C.int(32))) // TODO: disagrees with the spec https://github.com/ethereum/wiki/wiki/Ethash#mining if result.Cmp(target) <= 0 { @@ -402,7 +402,7 @@ func (pow *Ethash) verify(hash []byte, mixDigest []byte, difficulty *big.Int, bl C.ethash_light(ret, pAc.cache, pAc.params, chash, cnonce) - result := ethutil.Bytes2Big(C.GoBytes(unsafe.Pointer(&ret.result[0]), C.int(32))) + result := common.Bytes2Big(C.GoBytes(unsafe.Pointer(&ret.result[0]), C.int(32))) return result.Cmp(target) <= 0 } diff --git a/accounts/abi/numbers.go b/accounts/abi/numbers.go index 378f6541e..9205c005e 100644 --- a/accounts/abi/numbers.go +++ b/accounts/abi/numbers.go @@ -4,7 +4,7 @@ import ( "math/big" "reflect" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" ) var big_t = reflect.TypeOf(&big.Int{}) @@ -38,13 +38,13 @@ var big_ts = reflect.TypeOf([]*big.Int(nil)) // U256 will ensure unsigned 256bit on big nums func U256(n *big.Int) []byte { - return ethutil.LeftPadBytes(ethutil.U256(n).Bytes(), 32) + return common.LeftPadBytes(common.U256(n).Bytes(), 32) } func S256(n *big.Int) []byte { - sint := ethutil.S256(n) - ret := ethutil.LeftPadBytes(sint.Bytes(), 32) - if sint.Cmp(ethutil.Big0) < 0 { + sint := common.S256(n) + ret := common.LeftPadBytes(sint.Bytes(), 32) + if sint.Cmp(common.Big0) < 0 { for i, b := range ret { if b == 0 { ret[i] = 1 diff --git a/accounts/abi/type.go b/accounts/abi/type.go index b2d4abbd3..56520b672 100644 --- a/accounts/abi/type.go +++ b/accounts/abi/type.go @@ -6,7 +6,7 @@ import ( "regexp" "strconv" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" ) const ( @@ -157,7 +157,7 @@ func (t Type) pack(v interface{}) ([]byte, error) { if t.Size > -1 && value.Len() > t.Size { return nil, fmt.Errorf("%v out of bound. %d for %d", value.Kind(), value.Len(), t.Size) } - return []byte(ethutil.LeftPadString(t.String(), 32)), nil + return []byte(common.LeftPadString(t.String(), 32)), nil case reflect.Slice: if t.Size > -1 && value.Len() > t.Size { return nil, fmt.Errorf("%v out of bound. %d for %d", value.Kind(), value.Len(), t.Size) @@ -165,7 +165,7 @@ func (t Type) pack(v interface{}) ([]byte, error) { // Address is a special slice. The slice acts as one rather than a list of elements. if t.T == AddressTy { - return ethutil.LeftPadBytes(v.([]byte), 32), nil + return common.LeftPadBytes(v.([]byte), 32), nil } // Signed / Unsigned check @@ -180,9 +180,9 @@ func (t Type) pack(v interface{}) ([]byte, error) { return packed, nil case reflect.Bool: if value.Bool() { - return ethutil.LeftPadBytes(ethutil.Big1.Bytes(), 32), nil + return common.LeftPadBytes(common.Big1.Bytes(), 32), nil } else { - return ethutil.LeftPadBytes(ethutil.Big0.Bytes(), 32), nil + return common.LeftPadBytes(common.Big0.Bytes(), 32), nil } } diff --git a/blockpool/blockpool_test.go b/blockpool/blockpool_test.go index bca48c6ca..411779057 100644 --- a/blockpool/blockpool_test.go +++ b/blockpool/blockpool_test.go @@ -6,7 +6,7 @@ import ( "github.com/ethereum/go-ethereum/blockpool/test" "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" ) func TestPeerWithKnownBlock(t *testing.T) { @@ -69,9 +69,9 @@ func TestPeerPromotionByOptionalTdOnBlock(t *testing.T) { hashes := blockPoolTester.hashPool.IndexesToHashes([]int{2, 3}) peer1.waitBlocksRequests(3) blockPool.AddBlock(&types.Block{ - HeaderHash: ethutil.Bytes(hashes[1]), - ParentHeaderHash: ethutil.Bytes(hashes[0]), - Td: ethutil.Big3, + HeaderHash: common.Bytes(hashes[1]), + ParentHeaderHash: common.Bytes(hashes[0]), + Td: common.Big3, }, "peer1") blockPool.RemovePeer("peer2") diff --git a/blockpool/blockpool_util_test.go b/blockpool/blockpool_util_test.go index 8f0c8baa0..9ac996bca 100644 --- a/blockpool/blockpool_util_test.go +++ b/blockpool/blockpool_util_test.go @@ -10,7 +10,7 @@ import ( "github.com/ethereum/go-ethereum/blockpool/test" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/errs" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/pow" ) @@ -315,7 +315,7 @@ func (self *peerTester) sendBlocks(indexes ...int) { hashes := self.hashPool.IndexesToHashes(indexes) for i := 1; i < len(hashes); i++ { fmt.Printf("adding block %v %x\n", indexes[i], hashes[i][:4]) - self.blockPool.AddBlock(&types.Block{HeaderHash: ethutil.Bytes(hashes[i]), ParentHeaderHash: ethutil.Bytes(hashes[i-1])}, self.id) + self.blockPool.AddBlock(&types.Block{HeaderHash: common.Bytes(hashes[i]), ParentHeaderHash: common.Bytes(hashes[i-1])}, self.id) } } diff --git a/blockpool/peers.go b/blockpool/peers.go index d56e270ab..5f4889792 100644 --- a/blockpool/peers.go +++ b/blockpool/peers.go @@ -10,7 +10,7 @@ import ( "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/errs" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" ) type peer struct { @@ -230,7 +230,7 @@ func (self *peers) addPeer( } best = true } else { - currentTD := ethutil.Big0 + currentTD := common.Big0 if self.best != nil { currentTD = self.best.td } @@ -264,7 +264,7 @@ func (self *peers) removePeer(id string) { if self.best == p { var newp *peer // FIXME: own TD - max := ethutil.Big0 + max := common.Big0 // peer with the highest self-acclaimed TD is chosen for _, pp := range self.peers { if pp.td.Cmp(max) > 0 { diff --git a/cmd/disasm/main.go b/cmd/disasm/main.go index c07246b00..5d42121b6 100644 --- a/cmd/disasm/main.go +++ b/cmd/disasm/main.go @@ -5,7 +5,7 @@ import ( "io/ioutil" "os" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/vm" ) @@ -15,7 +15,7 @@ func main() { fmt.Println(err) os.Exit(1) } - code = ethutil.Hex2Bytes(string(code[:len(code)-1])) + code = common.Hex2Bytes(string(code[:len(code)-1])) fmt.Printf("%x\n", code) for pc := uint64(0); pc < uint64(len(code)); pc++ { diff --git a/cmd/ethereum/blocktest.go b/cmd/ethereum/blocktest.go index 1bb3809cf..e6d701d2c 100644 --- a/cmd/ethereum/blocktest.go +++ b/cmd/ethereum/blocktest.go @@ -7,7 +7,7 @@ import ( "github.com/ethereum/go-ethereum/cmd/utils" "github.com/ethereum/go-ethereum/eth" "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/tests" ) @@ -41,7 +41,7 @@ func runblocktest(ctx *cli.Context) { } cfg := utils.MakeEthConfig(ClientIdentifier, Version, ctx) - cfg.NewDB = func(path string) (ethutil.Database, error) { return ethdb.NewMemDatabase() } + cfg.NewDB = func(path string) (common.Database, error) { return ethdb.NewMemDatabase() } ethereum, err := eth.New(cfg) if err != nil { utils.Fatalf("%v", err) diff --git a/cmd/ethereum/js.go b/cmd/ethereum/js.go index 3b98b588e..a3c5f5d2d 100644 --- a/cmd/ethereum/js.go +++ b/cmd/ethereum/js.go @@ -27,7 +27,7 @@ import ( "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/eth" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/javascript" "github.com/ethereum/go-ethereum/state" "github.com/ethereum/go-ethereum/xeth" @@ -226,7 +226,7 @@ func (self *jsre) dump(call otto.FunctionCall) otto.Value { block = self.ethereum.ChainManager().GetBlockByNumber(uint64(num)) } else if call.Argument(0).IsString() { hash, _ := call.Argument(0).ToString() - block = self.ethereum.ChainManager().GetBlock(ethutil.Hex2Bytes(hash)) + block = self.ethereum.ChainManager().GetBlock(common.Hex2Bytes(hash)) } else { fmt.Println("invalid argument for dump. Either hex string or number") } @@ -285,7 +285,7 @@ func (self *jsre) export(call otto.FunctionCall) otto.Value { data := self.ethereum.ChainManager().Export() - if err := ethutil.WriteFile(fn, data); err != nil { + if err := common.WriteFile(fn, data); err != nil { fmt.Println(err) return otto.FalseValue() } diff --git a/cmd/ethereum/main.go b/cmd/ethereum/main.go index 53746627a..1efea927f 100644 --- a/cmd/ethereum/main.go +++ b/cmd/ethereum/main.go @@ -33,7 +33,7 @@ import ( "github.com/ethereum/go-ethereum/cmd/utils" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/eth" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/state" "github.com/peterh/liner" @@ -200,7 +200,7 @@ func startEth(ctx *cli.Context, eth *eth.Ethereum) { } am := eth.AccountManager() // Attempt to unlock the account - err := am.Unlock(ethutil.FromHex(split[0]), split[1]) + err := am.Unlock(common.FromHex(split[0]), split[1]) if err != nil { utils.Fatalf("Unlock account failed '%v'", err) } @@ -284,7 +284,7 @@ func dump(ctx *cli.Context) { for _, arg := range ctx.Args() { var block *types.Block if hashish(arg) { - block = chainmgr.GetBlock(ethutil.Hex2Bytes(arg)) + block = chainmgr.GetBlock(common.Hex2Bytes(arg)) } else { num, _ := strconv.Atoi(arg) block = chainmgr.GetBlockByNumber(uint64(num)) diff --git a/cmd/ethtest/main.go b/cmd/ethtest/main.go index bbcde4c56..23ae9e525 100644 --- a/cmd/ethtest/main.go +++ b/cmd/ethtest/main.go @@ -34,7 +34,7 @@ import ( "strings" "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/state" "github.com/ethereum/go-ethereum/tests/helper" @@ -48,13 +48,13 @@ type Log struct { BloomF string `json:"bloom"` } -func (self Log) Address() []byte { return ethutil.Hex2Bytes(self.AddressF) } -func (self Log) Data() []byte { return ethutil.Hex2Bytes(self.DataF) } +func (self Log) Address() []byte { return common.Hex2Bytes(self.AddressF) } +func (self Log) Data() []byte { return common.Hex2Bytes(self.DataF) } func (self Log) RlpData() interface{} { return nil } func (self Log) Topics() [][]byte { t := make([][]byte, len(self.TopicsF)) for i, topic := range self.TopicsF { - t[i] = ethutil.Hex2Bytes(topic) + t[i] = common.Hex2Bytes(topic) } return t } @@ -66,15 +66,15 @@ type Account struct { Storage map[string]string } -func StateObjectFromAccount(db ethutil.Database, addr string, account Account) *state.StateObject { - obj := state.NewStateObject(ethutil.Hex2Bytes(addr), db) - obj.SetBalance(ethutil.Big(account.Balance)) +func StateObjectFromAccount(db common.Database, addr string, account Account) *state.StateObject { + obj := state.NewStateObject(common.Hex2Bytes(addr), db) + obj.SetBalance(common.Big(account.Balance)) - if ethutil.IsHex(account.Code) { + if common.IsHex(account.Code) { account.Code = account.Code[2:] } - obj.SetCode(ethutil.Hex2Bytes(account.Code)) - obj.SetNonce(ethutil.Big(account.Nonce).Uint64()) + obj.SetCode(common.Hex2Bytes(account.Code)) + obj.SetNonce(common.Big(account.Nonce).Uint64()) return obj } @@ -147,8 +147,8 @@ func RunVmTest(r io.Reader) (failed int) { } if len(test.Exec) == 0 { - if obj.Balance().Cmp(ethutil.Big(account.Balance)) != 0 { - fmt.Printf("FAIL: %s's : (%x) balance failed. Expected %v, got %v => %v\n", name, obj.Address()[:4], account.Balance, obj.Balance(), new(big.Int).Sub(ethutil.Big(account.Balance), obj.Balance())) + if obj.Balance().Cmp(common.Big(account.Balance)) != 0 { + fmt.Printf("FAIL: %s's : (%x) balance failed. Expected %v, got %v => %v\n", name, obj.Address()[:4], account.Balance, obj.Balance(), new(big.Int).Sub(common.Big(account.Balance), obj.Balance())) failed = 1 } } @@ -158,13 +158,13 @@ func RunVmTest(r io.Reader) (failed int) { vexp := helper.FromHex(value) if bytes.Compare(v, vexp) != 0 { - fmt.Printf("FAIL: %s's : (%x: %s) storage failed. Expected %x, got %x (%v %v)\n", name, obj.Address()[0:4], addr, vexp, v, ethutil.BigD(vexp), ethutil.BigD(v)) + fmt.Printf("FAIL: %s's : (%x: %s) storage failed. Expected %x, got %x (%v %v)\n", name, obj.Address()[0:4], addr, vexp, v, common.BigD(vexp), common.BigD(v)) failed = 1 } } } - if !bytes.Equal(ethutil.Hex2Bytes(test.PostStateRoot), statedb.Root()) { + if !bytes.Equal(common.Hex2Bytes(test.PostStateRoot), statedb.Root()) { fmt.Printf("FAIL: %s's : Post state root error. Expected %s, got %x\n", name, test.PostStateRoot, statedb.Root()) failed = 1 } @@ -178,8 +178,8 @@ func RunVmTest(r io.Reader) (failed int) { fmt.Println("A", test.Logs) fmt.Println("B", logs) for i, log := range test.Logs { - genBloom := ethutil.LeftPadBytes(types.LogsBloom(state.Logs{logs[i]}).Bytes(), 256) - if !bytes.Equal(genBloom, ethutil.Hex2Bytes(log.BloomF)) { + genBloom := common.LeftPadBytes(types.LogsBloom(state.Logs{logs[i]}).Bytes(), 256) + if !bytes.Equal(genBloom, common.Hex2Bytes(log.BloomF)) { t.Errorf("bloom mismatch") } } diff --git a/cmd/evm/main.go b/cmd/evm/main.go index 960558bb4..af15dd4d4 100644 --- a/cmd/evm/main.go +++ b/cmd/evm/main.go @@ -33,7 +33,7 @@ import ( "github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/state" "github.com/ethereum/go-ethereum/vm" @@ -63,13 +63,13 @@ func main() { statedb := state.New(nil, db) sender := statedb.NewStateObject([]byte("sender")) receiver := statedb.NewStateObject([]byte("receiver")) - receiver.SetCode(ethutil.Hex2Bytes(*code)) + receiver.SetCode(common.Hex2Bytes(*code)) - vmenv := NewEnv(statedb, []byte("evmuser"), ethutil.Big(*value)) + vmenv := NewEnv(statedb, []byte("evmuser"), common.Big(*value)) tstart := time.Now() - ret, e := vmenv.Call(sender, receiver.Address(), ethutil.Hex2Bytes(*data), ethutil.Big(*gas), ethutil.Big(*price), ethutil.Big(*value)) + ret, e := vmenv.Call(sender, receiver.Address(), common.Hex2Bytes(*data), common.Big(*gas), common.Big(*price), common.Big(*value)) logger.Flush() if e != nil { @@ -117,11 +117,11 @@ func NewEnv(state *state.StateDB, transactor []byte, value *big.Int) *VMEnv { func (self *VMEnv) State() *state.StateDB { return self.state } func (self *VMEnv) Origin() []byte { return self.transactor } -func (self *VMEnv) BlockNumber() *big.Int { return ethutil.Big0 } +func (self *VMEnv) BlockNumber() *big.Int { return common.Big0 } func (self *VMEnv) PrevHash() []byte { return make([]byte, 32) } func (self *VMEnv) Coinbase() []byte { return self.transactor } func (self *VMEnv) Time() int64 { return self.time } -func (self *VMEnv) Difficulty() *big.Int { return ethutil.Big1 } +func (self *VMEnv) Difficulty() *big.Int { return common.Big1 } func (self *VMEnv) BlockHash() []byte { return make([]byte, 32) } func (self *VMEnv) Value() *big.Int { return self.value } func (self *VMEnv) GasLimit() *big.Int { return big.NewInt(1000000000) } diff --git a/cmd/mist/bindings.go b/cmd/mist/bindings.go index b56c0dddf..1371c752c 100644 --- a/cmd/mist/bindings.go +++ b/cmd/mist/bindings.go @@ -27,7 +27,7 @@ import ( "github.com/ethereum/go-ethereum/cmd/utils" "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/state" ) @@ -39,13 +39,13 @@ type plugin struct { func (gui *Gui) Transact(from, recipient, value, gas, gasPrice, d string) (string, error) { var data string if len(recipient) == 0 { - code, err := ethutil.Compile(d, false) + code, err := common.Compile(d, false) if err != nil { return "", err } - data = ethutil.Bytes2Hex(code) + data = common.Bytes2Hex(code) } else { - data = ethutil.Bytes2Hex(utils.FormatTransactionData(d)) + data = common.Bytes2Hex(utils.FormatTransactionData(d)) } return gui.xeth.Transact(from, recipient, value, gas, gasPrice, data) @@ -55,14 +55,14 @@ func (self *Gui) AddPlugin(pluginPath string) { self.plugins[pluginPath] = plugin{Name: pluginPath, Path: pluginPath} json, _ := json.MarshalIndent(self.plugins, "", " ") - ethutil.WriteFile(self.eth.DataDir+"/plugins.json", json) + common.WriteFile(self.eth.DataDir+"/plugins.json", json) } func (self *Gui) RemovePlugin(pluginPath string) { delete(self.plugins, pluginPath) json, _ := json.MarshalIndent(self.plugins, "", " ") - ethutil.WriteFile(self.eth.DataDir+"/plugins.json", json) + common.WriteFile(self.eth.DataDir+"/plugins.json", json) } func (self *Gui) DumpState(hash, path string) { @@ -76,7 +76,7 @@ func (self *Gui) DumpState(hash, path string) { i, _ := strconv.Atoi(hash[1:]) block = self.eth.ChainManager().GetBlockByNumber(uint64(i)) } else { - block = self.eth.ChainManager().GetBlock(ethutil.Hex2Bytes(hash)) + block = self.eth.ChainManager().GetBlock(common.Hex2Bytes(hash)) } if block == nil { diff --git a/cmd/mist/gui.go b/cmd/mist/gui.go index a49e9f6f8..476b441c8 100644 --- a/cmd/mist/gui.go +++ b/cmd/mist/gui.go @@ -37,7 +37,7 @@ import ( "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/eth" "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/ui/qt/qwhisper" "github.com/ethereum/go-ethereum/xeth" @@ -93,7 +93,7 @@ func NewWindow(ethereum *eth.Ethereum) *Gui { plugins: make(map[string]plugin), serviceEvents: make(chan ServEv, 1), } - data, _ := ethutil.ReadAllFile(path.Join(ethereum.DataDir, "plugins.json")) + data, _ := common.ReadAllFile(path.Join(ethereum.DataDir, "plugins.json")) json.Unmarshal([]byte(data), &gui.plugins) return gui @@ -200,7 +200,7 @@ func (gui *Gui) loadAddressBook() { it := nameReg.Trie().Iterator() for it.Next() { if it.Key[0] != 0 { - view.Call("addAddress", struct{ Name, Address string }{string(it.Key), ethutil.Bytes2Hex(it.Value)}) + view.Call("addAddress", struct{ Name, Address string }{string(it.Key), common.Bytes2Hex(it.Value)}) } } @@ -221,7 +221,7 @@ func (self *Gui) loadMergedMiningOptions() { Checked bool Name, Address string Id, ItemId int - }{false, string(it.Key), ethutil.Bytes2Hex(it.Value), 0, i}) + }{false, string(it.Key), common.Bytes2Hex(it.Value), 0, i}) i++ @@ -240,8 +240,8 @@ func (gui *Gui) insertTransaction(window string, tx *types.Transaction) { var ( ptx = xeth.NewTx(tx) - send = ethutil.Bytes2Hex(tx.From()) - rec = ethutil.Bytes2Hex(tx.To()) + send = common.Bytes2Hex(tx.From()) + rec = common.Bytes2Hex(tx.To()) ) ptx.Sender = send ptx.Address = rec @@ -265,7 +265,7 @@ func (gui *Gui) readPreviousTransactions() { } func (gui *Gui) processBlock(block *types.Block, initial bool) { - name := ethutil.Bytes2Hex(block.Coinbase()) + name := common.Bytes2Hex(block.Coinbase()) b := xeth.NewBlock(block) b.Name = name @@ -279,10 +279,10 @@ func (gui *Gui) setWalletValue(amount, unconfirmedFunds *big.Int) { if unconfirmedFunds.Cmp(big.NewInt(0)) < 0 { pos = "-" } - val := ethutil.CurrencyToString(new(big.Int).Abs(ethutil.BigCopy(unconfirmedFunds))) - str = fmt.Sprintf("%v (%s %v)", ethutil.CurrencyToString(amount), pos, val) + val := common.CurrencyToString(new(big.Int).Abs(common.BigCopy(unconfirmedFunds))) + str = fmt.Sprintf("%v (%s %v)", common.CurrencyToString(amount), pos, val) } else { - str = fmt.Sprintf("%v", ethutil.CurrencyToString(amount)) + str = fmt.Sprintf("%v", common.CurrencyToString(amount)) } gui.win.Root().Call("setWalletValue", str) diff --git a/cmd/mist/html_container.go b/cmd/mist/html_container.go index e4ea57b9b..195e81073 100644 --- a/cmd/mist/html_container.go +++ b/cmd/mist/html_container.go @@ -30,7 +30,7 @@ import ( "path/filepath" "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/xeth" "github.com/howeyc/fsnotify" "github.com/obscuren/qml" @@ -62,7 +62,7 @@ func (app *HtmlApplication) Create() error { return errors.New("Ethereum package not yet supported") // TODO - //ethutil.OpenPackage(app.path) + //common.OpenPackage(app.path) } win := component.CreateWindow(nil) @@ -80,7 +80,7 @@ func (app *HtmlApplication) RootFolder() string { if err != nil { return "" } - return path.Dir(ethutil.WindonizePath(folder.RequestURI())) + return path.Dir(common.WindonizePath(folder.RequestURI())) } func (app *HtmlApplication) RecursiveFolders() []os.FileInfo { files, _ := ioutil.ReadDir(app.RootFolder()) @@ -139,7 +139,7 @@ func (app *HtmlApplication) Window() *qml.Window { } func (app *HtmlApplication) NewBlock(block *types.Block) { - b := &xeth.Block{Number: int(block.NumberU64()), Hash: ethutil.Bytes2Hex(block.Hash())} + b := &xeth.Block{Number: int(block.NumberU64()), Hash: common.Bytes2Hex(block.Hash())} app.webView.Call("onNewBlockCb", b) } diff --git a/cmd/mist/main.go b/cmd/mist/main.go index 4116783c9..256c08691 100644 --- a/cmd/mist/main.go +++ b/cmd/mist/main.go @@ -29,7 +29,7 @@ import ( "github.com/codegangsta/cli" "github.com/ethereum/go-ethereum/cmd/utils" "github.com/ethereum/go-ethereum/eth" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/ui/qt/webengine" "github.com/obscuren/qml" @@ -45,7 +45,7 @@ var ( assetPathFlag = cli.StringFlag{ Name: "asset_path", Usage: "absolute path to GUI assets directory", - Value: ethutil.DefaultAssetPath(), + Value: common.DefaultAssetPath(), } ) diff --git a/cmd/mist/qml_container.go b/cmd/mist/qml_container.go index 16a055bc0..778ef0e40 100644 --- a/cmd/mist/qml_container.go +++ b/cmd/mist/qml_container.go @@ -25,7 +25,7 @@ import ( "runtime" "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/xeth" "github.com/obscuren/qml" ) @@ -68,7 +68,7 @@ func (app *QmlApplication) NewWatcher(quitChan chan bool) { // Events func (app *QmlApplication) NewBlock(block *types.Block) { - pblock := &xeth.Block{Number: int(block.NumberU64()), Hash: ethutil.Bytes2Hex(block.Hash())} + pblock := &xeth.Block{Number: int(block.NumberU64()), Hash: common.Bytes2Hex(block.Hash())} app.win.Call("onNewBlockCb", pblock) } diff --git a/cmd/mist/ui_lib.go b/cmd/mist/ui_lib.go index cc213b49a..b33b81267 100644 --- a/cmd/mist/ui_lib.go +++ b/cmd/mist/ui_lib.go @@ -27,7 +27,7 @@ import ( "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/eth" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/event/filter" "github.com/ethereum/go-ethereum/javascript" "github.com/ethereum/go-ethereum/xeth" @@ -69,7 +69,7 @@ func (self *UiLib) Notef(args []interface{}) { } func (self *UiLib) ImportTx(rlpTx string) { - tx := types.NewTransactionFromBytes(ethutil.Hex2Bytes(rlpTx)) + tx := types.NewTransactionFromBytes(common.Hex2Bytes(rlpTx)) err := self.eth.TxPool().Add(tx) if err != nil { guilogger.Infoln("import tx failed ", err) @@ -138,12 +138,12 @@ func (self *UiLib) Transact(params map[string]interface{}) (string, error) { } func (self *UiLib) Compile(code string) (string, error) { - bcode, err := ethutil.Compile(code, false) + bcode, err := common.Compile(code, false) if err != nil { return err.Error(), err } - return ethutil.Bytes2Hex(bcode), err + return common.Bytes2Hex(bcode), err } func (self *UiLib) Call(params map[string]interface{}) (string, error) { @@ -163,8 +163,8 @@ func (self *UiLib) AddLocalTransaction(to, data, gas, gasPrice, value string) in return 0 /* return self.miner.AddLocalTx(&miner.LocalTx{ - To: ethutil.Hex2Bytes(to), - Data: ethutil.Hex2Bytes(data), + To: common.Hex2Bytes(to), + Data: common.Hex2Bytes(data), Gas: gas, GasPrice: gasPrice, Value: value, @@ -187,7 +187,7 @@ func (self *UiLib) ToggleMining() bool { } func (self *UiLib) ToHex(data string) string { - return "0x" + ethutil.Bytes2Hex([]byte(data)) + return "0x" + common.Bytes2Hex([]byte(data)) } func (self *UiLib) ToAscii(data string) string { @@ -195,7 +195,7 @@ func (self *UiLib) ToAscii(data string) string { if len(data) > 1 && data[0:2] == "0x" { start = 2 } - return string(ethutil.Hex2Bytes(data[start:])) + return string(common.Hex2Bytes(data[start:])) } /// Ethereum filter methods @@ -223,7 +223,7 @@ func (self *UiLib) NewFilterString(typ string, view *qml.Common) (id int) { return 0 } -func (self *UiLib) Messages(id int) *ethutil.List { +func (self *UiLib) Messages(id int) *common.List { /* TODO remove me filter := self.filterManager.GetFilter(id) if filter != nil { @@ -233,7 +233,7 @@ func (self *UiLib) Messages(id int) *ethutil.List { } */ - return ethutil.EmptyList() + return common.EmptyList() } func (self *UiLib) ReadFile(p string) string { @@ -275,14 +275,14 @@ func mapToTxParams(object map[string]interface{}) map[string]string { } for _, str := range data { - if ethutil.IsHex(str) { + if common.IsHex(str) { str = str[2:] if len(str) != 64 { - str = ethutil.LeftPadString(str, 64) + str = common.LeftPadString(str, 64) } } else { - str = ethutil.Bytes2Hex(ethutil.LeftPadBytes(ethutil.Big(str).Bytes(), 32)) + str = common.Bytes2Hex(common.LeftPadBytes(common.Big(str).Bytes(), 32)) } dataStr += str diff --git a/cmd/utils/cmd.go b/cmd/utils/cmd.go index 6b99b841f..74fd5334e 100644 --- a/cmd/utils/cmd.go +++ b/cmd/utils/cmd.go @@ -30,7 +30,7 @@ import ( "github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/eth" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/rlp" ) @@ -62,7 +62,7 @@ func RunInterruptCallbacks(sig os.Signal) { } func openLogFile(Datadir string, filename string) *os.File { - path := ethutil.AbsolutePath(Datadir, filename) + path := common.AbsolutePath(Datadir, filename) file, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) if err != nil { panic(fmt.Sprintf("error opening log file '%s': %v", filename, err)) @@ -132,10 +132,10 @@ func StartEthereumForTest(ethereum *eth.Ethereum) { } func FormatTransactionData(data string) []byte { - d := ethutil.StringToByteFunc(data, func(s string) (ret []byte) { + d := common.StringToByteFunc(data, func(s string) (ret []byte) { slice := regexp.MustCompile("\\n|\\s").Split(s, 1000000000) for _, dataItem := range slice { - d := ethutil.FormatData(dataItem) + d := common.FormatData(dataItem) ret = append(ret, d...) } return @@ -171,7 +171,7 @@ func ExportChain(chainmgr *core.ChainManager, fn string) error { data := chainmgr.Export() - if err := ethutil.WriteFile(fn, data); err != nil { + if err := common.WriteFile(fn, data); err != nil { return err } fmt.Printf("exported blockchain\n") diff --git a/cmd/utils/flags.go b/cmd/utils/flags.go index 6bcd7e811..95666e3c9 100644 --- a/cmd/utils/flags.go +++ b/cmd/utils/flags.go @@ -15,7 +15,7 @@ import ( "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/eth" "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/p2p/nat" @@ -87,7 +87,7 @@ var ( DataDirFlag = cli.StringFlag{ Name: "datadir", Usage: "Data directory to be used", - Value: ethutil.DefaultDataDir(), + Value: common.DefaultDataDir(), } MinerThreadsFlag = cli.IntFlag{ Name: "minerthreads", @@ -193,7 +193,7 @@ func GetNodeKey(ctx *cli.Context) (key *ecdsa.PrivateKey) { func MakeEthConfig(clientID, version string, ctx *cli.Context) *eth.Config { return ð.Config{ - Name: ethutil.MakeName(clientID, version), + Name: common.MakeName(clientID, version), DataDir: ctx.GlobalString(DataDirFlag.Name), LogFile: ctx.GlobalString(LogFileFlag.Name), LogLevel: ctx.GlobalInt(LogLevelFlag.Name), @@ -211,7 +211,7 @@ func MakeEthConfig(clientID, version string, ctx *cli.Context) *eth.Config { } } -func GetChain(ctx *cli.Context) (*core.ChainManager, ethutil.Database, ethutil.Database) { +func GetChain(ctx *cli.Context) (*core.ChainManager, common.Database, common.Database) { dataDir := ctx.GlobalString(DataDirFlag.Name) blockDb, err := ethdb.NewLDBDatabase(path.Join(dataDir, "blockchain")) if err != nil { diff --git a/common/.gitignore b/common/.gitignore new file mode 100644 index 000000000..f725d58d1 --- /dev/null +++ b/common/.gitignore @@ -0,0 +1,12 @@ +# See http://help.github.com/ignore-files/ for more about ignoring files. +# +# If you find yourself ignoring temporary files generated by your text editor +# or operating system, you probably want to add a global ignore instead: +# git config --global core.excludesfile ~/.gitignore_global + +/tmp +*/**/*un~ +*un~ +.DS_Store +*/**/.DS_Store + diff --git a/common/.travis.yml b/common/.travis.yml new file mode 100644 index 000000000..69359072d --- /dev/null +++ b/common/.travis.yml @@ -0,0 +1,3 @@ +language: go +go: + - 1.2 diff --git a/common/README.md b/common/README.md new file mode 100644 index 000000000..1ed56b71b --- /dev/null +++ b/common/README.md @@ -0,0 +1,139 @@ +# ethutil + +[![Build +Status](https://travis-ci.org/ethereum/go-ethereum.png?branch=master)](https://travis-ci.org/ethereum/go-ethereum) + +The ethutil package contains the ethereum utility library. + +# Installation + +`go get github.com/ethereum/ethutil-go` + +# Usage + +## RLP (Recursive Linear Prefix) Encoding + +RLP Encoding is an encoding scheme utilized by the Ethereum project. It +encodes any native value or list to string. + +More in depth information about the Encoding scheme see the [Wiki](http://wiki.ethereum.org/index.php/RLP) +article. + +```go +rlp := ethutil.Encode("doge") +fmt.Printf("%q\n", rlp) // => "\0x83dog" + +rlp = ethutil.Encode([]interface{}{"dog", "cat"}) +fmt.Printf("%q\n", rlp) // => "\0xc8\0x83dog\0x83cat" +decoded := ethutil.Decode(rlp) +fmt.Println(decoded) // => ["dog" "cat"] +``` + +## Patricia Trie + +Patricie Tree is a merkle trie utilized by the Ethereum project. + +More in depth information about the (modified) Patricia Trie can be +found on the [Wiki](http://wiki.ethereum.org/index.php/Patricia_Tree). + +The patricia trie uses a db as backend and could be anything as long as +it satisfies the Database interface found in `ethutil/db.go`. + +```go +db := NewDatabase() + +// db, root +trie := ethutil.NewTrie(db, "") + +trie.Put("puppy", "dog") +trie.Put("horse", "stallion") +trie.Put("do", "verb") +trie.Put("doge", "coin") + +// Look up the key "do" in the trie +out := trie.Get("do") +fmt.Println(out) // => verb + +trie.Delete("puppy") +``` + +The patricia trie, in combination with RLP, provides a robust, +cryptographically authenticated data structure that can be used to store +all (key, value) bindings. + +```go +// ... Create db/trie + +// Note that RLP uses interface slices as list +value := ethutil.Encode([]interface{}{"one", 2, "three", []interface{}{42}}) +// Store the RLP encoded value of the list +trie.Put("mykey", value) +``` + +## Value + +Value is a Generic Value which is used in combination with RLP data or +`([])interface{}` structures. It may serve as a bridge between RLP data +and actual real values and takes care of all the type checking and +casting. Unlike Go's `reflect.Value` it does not panic if it's unable to +cast to the requested value. It simple returns the base value of that +type (e.g. `Slice()` returns []interface{}, `Uint()` return 0, etc). + +### Creating a new Value + +`NewEmptyValue()` returns a new \*Value with it's initial value set to a +`[]interface{}` + +`AppendList()` appends a list to the current value. + +`Append(v)` appends the value (v) to the current value/list. + +```go +val := ethutil.NewEmptyValue().Append(1).Append("2") +val.AppendList().Append(3) +``` + +### Retrieving values + +`Get(i)` returns the `i` item in the list. + +`Uint()` returns the value as an unsigned int64. + +`Slice()` returns the value as a interface slice. + +`Str()` returns the value as a string. + +`Bytes()` returns the value as a byte slice. + +`Len()` assumes current to be a slice and returns its length. + +`Byte()` returns the value as a single byte. + +```go +val := ethutil.NewValue([]interface{}{1,"2",[]interface{}{3}}) +val.Get(0).Uint() // => 1 +val.Get(1).Str() // => "2" +s := val.Get(2) // => Value([]interface{}{3}) +s.Get(0).Uint() // => 3 +``` + +## Decoding + +Decoding streams of RLP data is simplified + +```go +val := ethutil.NewValueFromBytes(rlpData) +val.Get(0).Uint() +``` + +## Encoding + +Encoding from Value to RLP is done with the `Encode` method. The +underlying value can be anything RLP can encode (int, str, lists, bytes) + +```go +val := ethutil.NewValue([]interface{}{1,"2",[]interface{}{3}}) +rlp := val.Encode() +// Store the rlp data +Store(rlp) +``` diff --git a/common/big.go b/common/big.go new file mode 100644 index 000000000..750b28f85 --- /dev/null +++ b/common/big.go @@ -0,0 +1,123 @@ +package common + +import "math/big" + +// Big pow +// +// Returns the power of two big integers +func BigPow(a, b int) *big.Int { + c := new(big.Int) + c.Exp(big.NewInt(int64(a)), big.NewInt(int64(b)), big.NewInt(0)) + + return c +} + +// Big +// +// Shortcut for new(big.Int).SetString(..., 0) +func Big(num string) *big.Int { + n := new(big.Int) + n.SetString(num, 0) + + return n +} + +// BigD +// +// Shortcut for new(big.Int).SetBytes(...) +func Bytes2Big(data []byte) *big.Int { + n := new(big.Int) + n.SetBytes(data) + + return n +} +func BigD(data []byte) *big.Int { return Bytes2Big(data) } + +func String2Big(num string) *big.Int { + n := new(big.Int) + n.SetString(num, 0) + return n +} + +func BitTest(num *big.Int, i int) bool { + return num.Bit(i) > 0 +} + +// To256 +// +// "cast" the big int to a 256 big int (i.e., limit to) +var tt256 = new(big.Int).Lsh(big.NewInt(1), 256) +var tt256m1 = new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), 256), big.NewInt(1)) +var tt255 = new(big.Int).Lsh(big.NewInt(1), 255) + +func U256(x *big.Int) *big.Int { + //if x.Cmp(Big0) < 0 { + // return new(big.Int).Add(tt256, x) + // } + + x.And(x, tt256m1) + + return x +} + +func S256(x *big.Int) *big.Int { + if x.Cmp(tt255) < 0 { + return x + } else { + // We don't want to modify x, ever + return new(big.Int).Sub(x, tt256) + } +} + +func FirstBitSet(v *big.Int) int { + for i := 0; i < v.BitLen(); i++ { + if v.Bit(i) > 0 { + return i + } + } + + return v.BitLen() +} + +// Big to bytes +// +// Returns the bytes of a big integer with the size specified by **base** +// Attempts to pad the byte array with zeros. +func BigToBytes(num *big.Int, base int) []byte { + ret := make([]byte, base/8) + + if len(num.Bytes()) > base/8 { + return num.Bytes() + } + + return append(ret[:len(ret)-len(num.Bytes())], num.Bytes()...) +} + +// Big copy +// +// Creates a copy of the given big integer +func BigCopy(src *big.Int) *big.Int { + return new(big.Int).Set(src) +} + +// Big max +// +// Returns the maximum size big integer +func BigMax(x, y *big.Int) *big.Int { + if x.Cmp(y) <= 0 { + return y + } + + return x +} + +// Big min +// +// Returns the minimum size big integer +func BigMin(x, y *big.Int) *big.Int { + if x.Cmp(y) >= 0 { + return y + } + + return x +} diff --git a/common/big_test.go b/common/big_test.go new file mode 100644 index 000000000..cedbaf144 --- /dev/null +++ b/common/big_test.go @@ -0,0 +1,73 @@ +package common + +import ( + "bytes" + "testing" +) + +func TestMisc(t *testing.T) { + a := Big("10") + b := Big("57896044618658097711785492504343953926634992332820282019728792003956564819968") + c := []byte{1, 2, 3, 4} + z := BitTest(a, 1) + + if z != true { + t.Error("Expected true got", z) + } + + U256(a) + S256(a) + + U256(b) + S256(b) + + BigD(c) +} + +func TestBigMax(t *testing.T) { + a := Big("10") + b := Big("5") + + max1 := BigMax(a, b) + if max1 != a { + t.Errorf("Expected %d got %d", a, max1) + } + + max2 := BigMax(b, a) + if max2 != a { + t.Errorf("Expected %d got %d", a, max2) + } +} + +func TestBigMin(t *testing.T) { + a := Big("10") + b := Big("5") + + min1 := BigMin(a, b) + if min1 != b { + t.Errorf("Expected %d got %d", b, min1) + } + + min2 := BigMin(b, a) + if min2 != b { + t.Errorf("Expected %d got %d", b, min2) + } +} + +func TestBigCopy(t *testing.T) { + a := Big("10") + b := BigCopy(a) + c := Big("1000000000000") + y := BigToBytes(b, 16) + ybytes := []byte{0, 10} + z := BigToBytes(c, 16) + zbytes := []byte{232, 212, 165, 16, 0} + + if bytes.Compare(y, ybytes) != 0 { + t.Error("Got", ybytes) + } + + if bytes.Compare(z, zbytes) != 0 { + t.Error("Got", zbytes) + } +} diff --git a/common/bytes.go b/common/bytes.go new file mode 100644 index 000000000..4aef9a223 --- /dev/null +++ b/common/bytes.go @@ -0,0 +1,234 @@ +package common + +import ( + "bytes" + "encoding/binary" + "encoding/hex" + "fmt" + "math/big" + "strings" +) + +type Bytes []byte + +func (self Bytes) String() string { + return string(self) +} + +func DeleteFromByteSlice(s [][]byte, hash []byte) [][]byte { + for i, h := range s { + if bytes.Compare(h, hash) == 0 { + return append(s[:i:i], s[i+1:]...) + } + } + + return s +} + +// Number to bytes +// +// Returns the number in bytes with the specified base +func NumberToBytes(num interface{}, bits int) []byte { + buf := new(bytes.Buffer) + err := binary.Write(buf, binary.BigEndian, num) + if err != nil { + fmt.Println("NumberToBytes failed:", err) + } + + return buf.Bytes()[buf.Len()-(bits/8):] +} + +// Bytes to number +// +// Attempts to cast a byte slice to a unsigned integer +func BytesToNumber(b []byte) uint64 { + var number uint64 + + // Make sure the buffer is 64bits + data := make([]byte, 8) + data = append(data[:len(b)], b...) + + buf := bytes.NewReader(data) + err := binary.Read(buf, binary.BigEndian, &number) + if err != nil { + fmt.Println("BytesToNumber failed:", err) + } + + return number +} + +// Read variable int +// +// Read a variable length number in big endian byte order +func ReadVarInt(buff []byte) (ret uint64) { + switch l := len(buff); { + case l > 4: + d := LeftPadBytes(buff, 8) + binary.Read(bytes.NewReader(d), binary.BigEndian, &ret) + case l > 2: + var num uint32 + d := LeftPadBytes(buff, 4) + binary.Read(bytes.NewReader(d), binary.BigEndian, &num) + ret = uint64(num) + case l > 1: + var num uint16 + d := LeftPadBytes(buff, 2) + binary.Read(bytes.NewReader(d), binary.BigEndian, &num) + ret = uint64(num) + default: + var num uint8 + binary.Read(bytes.NewReader(buff), binary.BigEndian, &num) + ret = uint64(num) + } + + return +} + +// Binary length +// +// Returns the true binary length of the given number +func BinaryLength(num int) int { + if num == 0 { + return 0 + } + + return 1 + BinaryLength(num>>8) +} + +// Copy bytes +// +// Returns an exact copy of the provided bytes +func CopyBytes(b []byte) (copiedBytes []byte) { + copiedBytes = make([]byte, len(b)) + copy(copiedBytes, b) + + return +} + +func IsHex(str string) bool { + l := len(str) + return l >= 4 && l%2 == 0 && str[0:2] == "0x" +} + +func Bytes2Hex(d []byte) string { + return hex.EncodeToString(d) +} + +func Hex2Bytes(str string) []byte { + h, _ := hex.DecodeString(str) + + return h +} + +func StringToByteFunc(str string, cb func(str string) []byte) (ret []byte) { + if len(str) > 1 && str[0:2] == "0x" && !strings.Contains(str, "\n") { + ret = Hex2Bytes(str[2:]) + } else { + ret = cb(str) + } + + return +} + +func FormatData(data string) []byte { + if len(data) == 0 { + return nil + } + // Simple stupid + d := new(big.Int) + if data[0:1] == "\"" && data[len(data)-1:] == "\"" { + return RightPadBytes([]byte(data[1:len(data)-1]), 32) + } else if len(data) > 1 && data[:2] == "0x" { + d.SetBytes(Hex2Bytes(data[2:])) + } else { + d.SetString(data, 0) + } + + return BigToBytes(d, 256) +} + +func ParseData(data ...interface{}) (ret []byte) { + for _, item := range data { + switch t := item.(type) { + case string: + var str []byte + if IsHex(t) { + str = Hex2Bytes(t[2:]) + } else { + str = []byte(t) + } + + ret = append(ret, RightPadBytes(str, 32)...) + case []byte: + ret = append(ret, LeftPadBytes(t, 32)...) + } + } + + return +} + +func RightPadBytes(slice []byte, l int) []byte { + if l < len(slice) { + return slice + } + + padded := make([]byte, l) + copy(padded[0:len(slice)], slice) + + return padded +} + +func LeftPadBytes(slice []byte, l int) []byte { + if l < len(slice) { + return slice + } + + padded := make([]byte, l) + copy(padded[l-len(slice):], slice) + + return padded +} + +func LeftPadString(str string, l int) string { + if l < len(str) { + return str + } + + zeros := Bytes2Hex(make([]byte, (l-len(str))/2)) + + return zeros + str + +} + +func RightPadString(str string, l int) string { + if l < len(str) { + return str + } + + zeros := Bytes2Hex(make([]byte, (l-len(str))/2)) + + return str + zeros + +} + +func Address(slice []byte) (addr []byte) { + if len(slice) < 20 { + addr = LeftPadBytes(slice, 20) + } else if len(slice) > 20 { + addr = slice[len(slice)-20:] + } else { + addr = slice + } + + addr = CopyBytes(addr) + + return +} + +func ByteSliceToInterface(slice [][]byte) (ret []interface{}) { + for _, i := range slice { + ret = append(ret, i) + } + + return +} diff --git a/common/bytes_test.go b/common/bytes_test.go new file mode 100644 index 000000000..ec106bf4b --- /dev/null +++ b/common/bytes_test.go @@ -0,0 +1,193 @@ +package common + +import ( + checker "gopkg.in/check.v1" +) + +type BytesSuite struct{} + +var _ = checker.Suite(&BytesSuite{}) + +func (s *BytesSuite) TestByteString(c *checker.C) { + var data Bytes + data = []byte{102, 111, 111} + exp := "foo" + res := data.String() + + c.Assert(res, checker.Equals, exp) +} + +/* +func (s *BytesSuite) TestDeleteFromByteSlice(c *checker.C) { + data := []byte{1, 2, 3, 4} + slice := []byte{1, 2, 3, 4} + exp := []byte{1, 4} + res := DeleteFromByteSlice(data, slice) + + c.Assert(res, checker.DeepEquals, exp) +} + +*/ +func (s *BytesSuite) TestNumberToBytes(c *checker.C) { + // data1 := int(1) + // res1 := NumberToBytes(data1, 16) + // c.Check(res1, checker.Panics) + + var data2 float64 = 3.141592653 + exp2 := []byte{0xe9, 0x38} + res2 := NumberToBytes(data2, 16) + c.Assert(res2, checker.DeepEquals, exp2) +} + +func (s *BytesSuite) TestBytesToNumber(c *checker.C) { + datasmall := []byte{0xe9, 0x38, 0xe9, 0x38} + datalarge := []byte{0xe9, 0x38, 0xe9, 0x38, 0xe9, 0x38, 0xe9, 0x38} + + var expsmall uint64 = 0xe938e938 + var explarge uint64 = 0x0 + + ressmall := BytesToNumber(datasmall) + reslarge := BytesToNumber(datalarge) + + c.Assert(ressmall, checker.Equals, expsmall) + c.Assert(reslarge, checker.Equals, explarge) + +} + +func (s *BytesSuite) TestReadVarInt(c *checker.C) { + data8 := []byte{1, 2, 3, 4, 5, 6, 7, 8} + data4 := []byte{1, 2, 3, 4} + data2 := []byte{1, 2} + data1 := []byte{1} + + exp8 := uint64(72623859790382856) + exp4 := uint64(16909060) + exp2 := uint64(258) + exp1 := uint64(1) + + res8 := ReadVarInt(data8) + res4 := ReadVarInt(data4) + res2 := ReadVarInt(data2) + res1 := ReadVarInt(data1) + + c.Assert(res8, checker.Equals, exp8) + c.Assert(res4, checker.Equals, exp4) + c.Assert(res2, checker.Equals, exp2) + c.Assert(res1, checker.Equals, exp1) +} + +func (s *BytesSuite) TestBinaryLength(c *checker.C) { + data1 := 0 + data2 := 920987656789 + + exp1 := 0 + exp2 := 5 + + res1 := BinaryLength(data1) + res2 := BinaryLength(data2) + + c.Assert(res1, checker.Equals, exp1) + c.Assert(res2, checker.Equals, exp2) +} + +func (s *BytesSuite) TestCopyBytes(c *checker.C) { + data1 := []byte{1, 2, 3, 4} + exp1 := []byte{1, 2, 3, 4} + res1 := CopyBytes(data1) + c.Assert(res1, checker.DeepEquals, exp1) +} + +func (s *BytesSuite) TestIsHex(c *checker.C) { + data1 := "a9e67e" + exp1 := false + res1 := IsHex(data1) + c.Assert(res1, checker.DeepEquals, exp1) + + data2 := "0xa9e67e00" + exp2 := true + res2 := IsHex(data2) + c.Assert(res2, checker.DeepEquals, exp2) + +} + +func (s *BytesSuite) TestParseDataString(c *checker.C) { + res1 := ParseData("hello", "world", "0x0106") + data := "68656c6c6f000000000000000000000000000000000000000000000000000000776f726c640000000000000000000000000000000000000000000000000000000106000000000000000000000000000000000000000000000000000000000000" + exp1 := Hex2Bytes(data) + c.Assert(res1, checker.DeepEquals, exp1) +} + +func (s *BytesSuite) TestParseDataBytes(c *checker.C) { + data1 := []byte{232, 212, 165, 16, 0} + exp1 := []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 232, 212, 165, 16, 0} + + res1 := ParseData(data1) + c.Assert(res1, checker.DeepEquals, exp1) + +} + +func (s *BytesSuite) TestLeftPadBytes(c *checker.C) { + val1 := []byte{1, 2, 3, 4} + exp1 := []byte{0, 0, 0, 0, 1, 2, 3, 4} + + res1 := LeftPadBytes(val1, 8) + res2 := LeftPadBytes(val1, 2) + + c.Assert(res1, checker.DeepEquals, exp1) + c.Assert(res2, checker.DeepEquals, val1) +} + +func (s *BytesSuite) TestFormatData(c *checker.C) { + data1 := "" + data2 := "0xa9e67e00" + data3 := "a9e67e" + data4 := "\"a9e67e00\"" + + // exp1 := []byte{} + exp2 := []byte{00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 0xa9, 0xe6, 0x7e, 00} + exp3 := []byte{00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00} + exp4 := []byte{0x61, 0x39, 0x65, 0x36, 0x37, 0x65, 0x30, 0x30, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00} + + res1 := FormatData(data1) + res2 := FormatData(data2) + res3 := FormatData(data3) + res4 := FormatData(data4) + + c.Assert(res1, checker.IsNil) + c.Assert(res2, checker.DeepEquals, exp2) + c.Assert(res3, checker.DeepEquals, exp3) + c.Assert(res4, checker.DeepEquals, exp4) +} + +func (s *BytesSuite) TestRightPadBytes(c *checker.C) { + val := []byte{1, 2, 3, 4} + exp := []byte{1, 2, 3, 4, 0, 0, 0, 0} + + resstd := RightPadBytes(val, 8) + resshrt := RightPadBytes(val, 2) + + c.Assert(resstd, checker.DeepEquals, exp) + c.Assert(resshrt, checker.DeepEquals, val) +} + +func (s *BytesSuite) TestLeftPadString(c *checker.C) { + val := "test" + exp := "\x30\x30\x30\x30" + val + + resstd := LeftPadString(val, 8) + resshrt := LeftPadString(val, 2) + + c.Assert(resstd, checker.Equals, exp) + c.Assert(resshrt, checker.Equals, val) +} + +func (s *BytesSuite) TestRightPadString(c *checker.C) { + val := "test" + exp := val + "\x30\x30\x30\x30" + + resstd := RightPadString(val, 8) + resshrt := RightPadString(val, 2) + + c.Assert(resstd, checker.Equals, exp) + c.Assert(resshrt, checker.Equals, val) +} diff --git a/common/common.go b/common/common.go new file mode 100644 index 000000000..1371d18d4 --- /dev/null +++ b/common/common.go @@ -0,0 +1,165 @@ +package common + +import ( + "fmt" + "math/big" + "os" + "os/user" + "path" + "path/filepath" + "runtime" + "time" + + "github.com/kardianos/osext" +) + +// MakeName creates a node name that follows the ethereum convention +// for such names. It adds the operation system name and Go runtime version +// the name. +func MakeName(name, version string) string { + return fmt.Sprintf("%s/v%s/%s/%s", name, version, runtime.GOOS, runtime.Version()) +} + +func DefaultAssetPath() string { + var assetPath string + pwd, _ := os.Getwd() + srcdir := path.Join(os.Getenv("GOPATH"), "src", "github.com", "ethereum", "go-ethereum", "cmd", "mist") + + // If the current working directory is the go-ethereum dir + // assume a debug build and use the source directory as + // asset directory. + if pwd == srcdir { + assetPath = path.Join(pwd, "assets") + } else { + switch runtime.GOOS { + case "darwin": + // Get Binary Directory + exedir, _ := osext.ExecutableFolder() + assetPath = filepath.Join(exedir, "../Resources") + case "linux": + assetPath = "/usr/share/mist" + case "windows": + assetPath = "./assets" + default: + assetPath = "." + } + } + + // Check if the assetPath exists. If not, try the source directory + // This happens when binary is run from outside cmd/mist directory + if _, err := os.Stat(assetPath); os.IsNotExist(err) { + assetPath = path.Join(srcdir, "assets") + } + + return assetPath +} + +func DefaultDataDir() string { + usr, _ := user.Current() + if runtime.GOOS == "darwin" { + return path.Join(usr.HomeDir, "Library/Ethereum") + } else if runtime.GOOS == "windows" { + return path.Join(usr.HomeDir, "AppData/Roaming/Ethereum") + } else { + return path.Join(usr.HomeDir, ".ethereum") + } +} + +func FromHex(s string) []byte { + if len(s) > 1 { + if s[0:2] == "0x" { + s = s[2:] + } + if len(s)%2 == 1 { + s = "0" + s + } + return Hex2Bytes(s) + } + return nil +} +func IsWindows() bool { + return runtime.GOOS == "windows" +} + +func WindonizePath(path string) string { + if string(path[0]) == "/" && IsWindows() { + path = path[1:] + } + return path +} + +// The different number of units +var ( + Douglas = BigPow(10, 42) + Einstein = BigPow(10, 21) + Ether = BigPow(10, 18) + Finney = BigPow(10, 15) + Szabo = BigPow(10, 12) + Shannon = BigPow(10, 9) + Babbage = BigPow(10, 6) + Ada = BigPow(10, 3) + Wei = big.NewInt(1) +) + +// +// Currency to string +// Returns a string representing a human readable format +func CurrencyToString(num *big.Int) string { + var ( + fin *big.Int = num + denom string = "Wei" + ) + + switch { + case num.Cmp(Douglas) >= 0: + fin = new(big.Int).Div(num, Douglas) + denom = "Douglas" + case num.Cmp(Einstein) >= 0: + fin = new(big.Int).Div(num, Einstein) + denom = "Einstein" + case num.Cmp(Ether) >= 0: + fin = new(big.Int).Div(num, Ether) + denom = "Ether" + case num.Cmp(Finney) >= 0: + fin = new(big.Int).Div(num, Finney) + denom = "Finney" + case num.Cmp(Szabo) >= 0: + fin = new(big.Int).Div(num, Szabo) + denom = "Szabo" + case num.Cmp(Shannon) >= 0: + fin = new(big.Int).Div(num, Shannon) + denom = "Shannon" + case num.Cmp(Babbage) >= 0: + fin = new(big.Int).Div(num, Babbage) + denom = "Babbage" + case num.Cmp(Ada) >= 0: + fin = new(big.Int).Div(num, Ada) + denom = "Ada" + } + + // TODO add comment clarifying expected behavior + if len(fin.String()) > 5 { + return fmt.Sprintf("%sE%d %s", fin.String()[0:5], len(fin.String())-5, denom) + } + + return fmt.Sprintf("%v %s", fin, denom) +} + +// Common big integers often used +var ( + Big1 = big.NewInt(1) + Big2 = big.NewInt(2) + Big3 = big.NewInt(3) + Big0 = big.NewInt(0) + BigTrue = Big1 + BigFalse = Big0 + Big32 = big.NewInt(32) + Big256 = big.NewInt(0xff) + Big257 = big.NewInt(257) +) + +func Bench(pre string, cb func()) { + start := time.Now() + cb() + fmt.Println(pre, ": took:", time.Since(start)) +} diff --git a/common/common_test.go b/common/common_test.go new file mode 100644 index 000000000..c7ba87f90 --- /dev/null +++ b/common/common_test.go @@ -0,0 +1,89 @@ +package common + +import ( + "bytes" + "math/big" + "os" + "testing" + + checker "gopkg.in/check.v1" +) + +type CommonSuite struct{} + +var _ = checker.Suite(&CommonSuite{}) + +func (s *CommonSuite) TestOS(c *checker.C) { + expwin := (os.PathSeparator == '\\' && os.PathListSeparator == ';') + res := IsWindows() + + if !expwin { + c.Assert(res, checker.Equals, expwin, checker.Commentf("IsWindows is", res, "but path is", os.PathSeparator)) + } else { + c.Assert(res, checker.Not(checker.Equals), expwin, checker.Commentf("IsWindows is", res, "but path is", os.PathSeparator)) + } +} + +func (s *CommonSuite) TestWindonziePath(c *checker.C) { + iswindowspath := os.PathSeparator == '\\' + path := "/opt/eth/test/file.ext" + res := WindonizePath(path) + ressep := string(res[0]) + + if !iswindowspath { + c.Assert(ressep, checker.Equals, "/") + } else { + c.Assert(ressep, checker.Not(checker.Equals), "/") + } +} + +func (s *CommonSuite) TestCommon(c *checker.C) { + douglas := CurrencyToString(BigPow(10, 43)) + einstein := CurrencyToString(BigPow(10, 22)) + ether := CurrencyToString(BigPow(10, 19)) + finney := CurrencyToString(BigPow(10, 16)) + szabo := CurrencyToString(BigPow(10, 13)) + shannon := CurrencyToString(BigPow(10, 10)) + babbage := CurrencyToString(BigPow(10, 7)) + ada := CurrencyToString(BigPow(10, 4)) + wei := CurrencyToString(big.NewInt(10)) + + c.Assert(douglas, checker.Equals, "10 Douglas") + c.Assert(einstein, checker.Equals, "10 Einstein") + c.Assert(ether, checker.Equals, "10 Ether") + c.Assert(finney, checker.Equals, "10 Finney") + c.Assert(szabo, checker.Equals, "10 Szabo") + c.Assert(shannon, checker.Equals, "10 Shannon") + c.Assert(babbage, checker.Equals, "10 Babbage") + c.Assert(ada, checker.Equals, "10 Ada") + c.Assert(wei, checker.Equals, "10 Wei") +} + +func (s *CommonSuite) TestLarge(c *checker.C) { + douglaslarge := CurrencyToString(BigPow(100000000, 43)) + adalarge := CurrencyToString(BigPow(100000000, 4)) + weilarge := CurrencyToString(big.NewInt(100000000)) + + c.Assert(douglaslarge, checker.Equals, "10000E298 Douglas") + c.Assert(adalarge, checker.Equals, "10000E7 Einstein") + c.Assert(weilarge, checker.Equals, "100 Babbage") +} + +//fromHex +func TestFromHex(t *testing.T) { + input := "0x01" + expected := []byte{1} + result := FromHex(input) + if bytes.Compare(expected, result) != 0 { + t.Errorf("Expected % x got % x", expected, result) + } +} + +func TestFromHexOddLength(t *testing.T) { + input := "0x1" + expected := []byte{1} + result := FromHex(input) + if bytes.Compare(expected, result) != 0 { + t.Errorf("Expected % x got % x", expected, result) + } +} diff --git a/common/config.go b/common/config.go new file mode 100644 index 000000000..23a902bc1 --- /dev/null +++ b/common/config.go @@ -0,0 +1,67 @@ +package common + +import ( + "flag" + "fmt" + "os" + + "github.com/rakyll/globalconf" +) + +// Config struct +type ConfigManager struct { + ExecPath string + Debug bool + Diff bool + DiffType string + Paranoia bool + VmType int + + conf *globalconf.GlobalConf +} + +// Read config +// +// Initialize Config from Config File +func ReadConfig(ConfigFile string, Datadir string, EnvPrefix string) *ConfigManager { + if !FileExist(ConfigFile) { + // create ConfigFile if it does not exist, otherwise + // globalconf will panic when trying to persist flags. + fmt.Printf("config file '%s' doesn't exist, creating it\n", ConfigFile) + os.Create(ConfigFile) + } + g, err := globalconf.NewWithOptions(&globalconf.Options{ + Filename: ConfigFile, + EnvPrefix: EnvPrefix, + }) + if err != nil { + fmt.Println(err) + } else { + g.ParseAll() + } + cfg := &ConfigManager{ExecPath: Datadir, Debug: true, conf: g, Paranoia: true} + return cfg +} + +// provides persistence for flags +func (c *ConfigManager) Save(key string, value interface{}) { + f := &flag.Flag{Name: key, Value: newConfValue(value)} + c.conf.Set("", f) +} + +func (c *ConfigManager) Delete(key string) { + c.conf.Delete("", key) +} + +// private type implementing flag.Value +type confValue struct { + value string +} + +// generic constructor to allow persising non-string values directly +func newConfValue(value interface{}) *confValue { + return &confValue{fmt.Sprintf("%v", value)} +} + +func (self confValue) String() string { return self.value } +func (self confValue) Set(s string) error { self.value = s; return nil } diff --git a/common/db.go b/common/db.go new file mode 100644 index 000000000..6505e61c6 --- /dev/null +++ b/common/db.go @@ -0,0 +1,12 @@ +package common + +// Database interface +type Database interface { + Put(key []byte, value []byte) + Get(key []byte) ([]byte, error) + //GetKeys() []*Key + Delete(key []byte) error + LastKnownTD() []byte + Close() + Print() +} diff --git a/common/list.go b/common/list.go new file mode 100644 index 000000000..594a8a24b --- /dev/null +++ b/common/list.go @@ -0,0 +1,81 @@ +package common + +import ( + "encoding/json" + "reflect" + "sync" +) + +// The list type is an anonymous slice handler which can be used +// for containing any slice type to use in an environment which +// does not support slice types (e.g., JavaScript, QML) +type List struct { + mut sync.Mutex + val interface{} + list reflect.Value + Length int +} + +// Initialise a new list. Panics if non-slice type is given. +func NewList(t interface{}) *List { + list := reflect.ValueOf(t) + if list.Kind() != reflect.Slice { + panic("list container initialized with a non-slice type") + } + + return &List{sync.Mutex{}, t, list, list.Len()} +} + +func EmptyList() *List { + return NewList([]interface{}{}) +} + +// Get N element from the embedded slice. Returns nil if OOB. +func (self *List) Get(i int) interface{} { + if self.list.Len() > i { + self.mut.Lock() + defer self.mut.Unlock() + + i := self.list.Index(i).Interface() + + return i + } + + return nil +} + +func (self *List) GetAsJson(i int) interface{} { + e := self.Get(i) + + r, _ := json.Marshal(e) + + return string(r) +} + +// Appends value at the end of the slice. Panics when incompatible value +// is given. +func (self *List) Append(v interface{}) { + self.mut.Lock() + defer self.mut.Unlock() + + self.list = reflect.Append(self.list, reflect.ValueOf(v)) + self.Length = self.list.Len() +} + +// Returns the underlying slice as interface. +func (self *List) Interface() interface{} { + return self.list.Interface() +} + +// For JavaScript <3 +func (self *List) ToJSON() string { + // make(T, 0) != nil + list := make([]interface{}, 0) + for i := 0; i < self.Length; i++ { + list = append(list, self.Get(i)) + } + + data, _ := json.Marshal(list) + + return string(data) +} diff --git a/common/main_test.go b/common/main_test.go new file mode 100644 index 000000000..2bed278e6 --- /dev/null +++ b/common/main_test.go @@ -0,0 +1,9 @@ +package common + +import ( + "testing" + + checker "gopkg.in/check.v1" +) + +func Test(t *testing.T) { checker.TestingT(t) } diff --git a/common/math/dist.go b/common/math/dist.go new file mode 100644 index 000000000..0a0731971 --- /dev/null +++ b/common/math/dist.go @@ -0,0 +1,80 @@ +package math + +import ( + "math/big" + "sort" + + "github.com/ethereum/go-ethereum/common" +) + +type Summer interface { + Sum(i int) *big.Int + Len() int +} + +func Sum(slice Summer) (sum *big.Int) { + sum = new(big.Int) + + for i := 0; i < slice.Len(); i++ { + sum.Add(sum, slice.Sum(i)) + } + return +} + +type Vector struct { + Gas, Price *big.Int +} + +type VectorsBy func(v1, v2 Vector) bool + +func (self VectorsBy) Sort(vectors []Vector) { + bs := vectorSorter{ + vectors: vectors, + by: self, + } + sort.Sort(bs) +} + +type vectorSorter struct { + vectors []Vector + by func(v1, v2 Vector) bool +} + +func (v vectorSorter) Len() int { return len(v.vectors) } +func (v vectorSorter) Less(i, j int) bool { return v.by(v.vectors[i], v.vectors[j]) } +func (v vectorSorter) Swap(i, j int) { v.vectors[i], v.vectors[j] = v.vectors[j], v.vectors[i] } + +func PriceSort(v1, v2 Vector) bool { return v1.Price.Cmp(v2.Price) < 0 } +func GasSort(v1, v2 Vector) bool { return v1.Gas.Cmp(v2.Gas) < 0 } + +type vectorSummer struct { + vectors []Vector + by func(v Vector) *big.Int +} + +type VectorSum func(v Vector) *big.Int + +func (v VectorSum) Sum(vectors []Vector) *big.Int { + vs := vectorSummer{ + vectors: vectors, + by: v, + } + return Sum(vs) +} + +func (v vectorSummer) Len() int { return len(v.vectors) } +func (v vectorSummer) Sum(i int) *big.Int { return v.by(v.vectors[i]) } + +func GasSum(v Vector) *big.Int { return v.Gas } + +var etherInWei = new(big.Rat).SetInt(common.String2Big("1000000000000000000")) + +func GasPrice(bp, gl, ep *big.Int) *big.Int { + BP := new(big.Rat).SetInt(bp) + GL := new(big.Rat).SetInt(gl) + EP := new(big.Rat).SetInt(ep) + GP := new(big.Rat).Quo(BP, GL) + GP = GP.Quo(GP, EP) + + return GP.Mul(GP, etherInWei).Num() +} diff --git a/common/math/dist_test.go b/common/math/dist_test.go new file mode 100644 index 000000000..90e302f44 --- /dev/null +++ b/common/math/dist_test.go @@ -0,0 +1,66 @@ +package math + +import ( + "fmt" + "math/big" + "testing" +) + +type summer struct { + numbers []*big.Int +} + +func (s summer) Len() int { return len(s.numbers) } +func (s summer) Sum(i int) *big.Int { + return s.numbers[i] +} + +func TestSum(t *testing.T) { + summer := summer{numbers: []*big.Int{big.NewInt(1), big.NewInt(2), big.NewInt(3)}} + sum := Sum(summer) + if sum.Cmp(big.NewInt(6)) != 0 { + t.Errorf("not 6", sum) + } +} + +func TestDist(t *testing.T) { + var vectors = []Vector{ + Vector{big.NewInt(1000), big.NewInt(1234)}, + Vector{big.NewInt(500), big.NewInt(10023)}, + Vector{big.NewInt(1034), big.NewInt(1987)}, + Vector{big.NewInt(1034), big.NewInt(1987)}, + Vector{big.NewInt(8983), big.NewInt(1977)}, + Vector{big.NewInt(98382), big.NewInt(1887)}, + Vector{big.NewInt(12398), big.NewInt(1287)}, + Vector{big.NewInt(12398), big.NewInt(1487)}, + Vector{big.NewInt(12398), big.NewInt(1987)}, + Vector{big.NewInt(12398), big.NewInt(128)}, + Vector{big.NewInt(12398), big.NewInt(1987)}, + Vector{big.NewInt(1398), big.NewInt(187)}, + Vector{big.NewInt(12328), big.NewInt(1927)}, + Vector{big.NewInt(12398), big.NewInt(1987)}, + Vector{big.NewInt(22398), big.NewInt(1287)}, + Vector{big.NewInt(1370), big.NewInt(1981)}, + Vector{big.NewInt(12398), big.NewInt(1957)}, + Vector{big.NewInt(42198), big.NewInt(1987)}, + } + + VectorsBy(GasSort).Sort(vectors) + fmt.Println(vectors) + + BP := big.NewInt(15) + GL := big.NewInt(1000000) + EP := big.NewInt(100) + fmt.Println("BP", BP, "GL", GL, "EP", EP) + GP := GasPrice(BP, GL, EP) + fmt.Println("GP =", GP, "Wei per GU") + + S := len(vectors) / 4 + fmt.Println("L", len(vectors), "S", S) + for i := 1; i <= S*4; i += S { + fmt.Printf("T%d = %v\n", i, vectors[i]) + } + + g := VectorSum(GasSum).Sum(vectors) + fmt.Printf("G = ∑g* (%v)\n", g) +} diff --git a/common/natspec/natspec.go b/common/natspec/natspec.go new file mode 100644 index 000000000..793bf59ae --- /dev/null +++ b/common/natspec/natspec.go @@ -0,0 +1,63 @@ +package natspec + +import ( + "fmt" + "github.com/obscuren/otto" +) + +type NatSpec struct { + jsvm *otto.Otto +} + +// TODO: should initialise with abi and userdoc jsons +func New() (self *NatSpec, err error) { + + self = new(NatSpec) + self.jsvm = otto.New() + + _, err = self.jsvm.Run(natspecJS) + if err != nil { + return + } + _, err = self.jsvm.Run("var natspec = require('natspec');") + if err != nil { + return + } + + return +} + +func (self *NatSpec) Notice(transaction, abi, method, expression string) (string, error) { + var err error + if _, err = self.jsvm.Run("var transaction = " + transaction + ";"); err != nil { + return "", fmt.Errorf("natspec.js error setting transaction: %v", err) + } + + if _, err = self.jsvm.Run("var abi = " + abi + ";"); err != nil { + return "", fmt.Errorf("natspec.js error setting abi: %v", err) + } + + if _, err = self.jsvm.Run("var method = '" + method + "';"); err != nil { + return "", fmt.Errorf("natspec.js error setting method: %v", err) + } + + if _, err = self.jsvm.Run("var expression = \"" + expression + "\";"); err != nil { + return "", fmt.Errorf("natspec.js error setting expression: %v", err) + } + + self.jsvm.Run("var call = {method: method,abi: abi,transaction: transaction};") + value, err := self.jsvm.Run("natspec.evaluateExpression(expression, call);") + if err != nil { + return "", fmt.Errorf("natspec.js error evaluating expression: %v", err) + } + evalError := "Natspec evaluation failed, wrong input params" + if value.String() == evalError { + return "", fmt.Errorf("natspec.js error evaluating expression: wrong input params in expression '%s'", expression) + } + if len(value.String()) == 0 { + return "", fmt.Errorf("natspec.js error evaluating expression") + } + + return value.String(), nil + +} diff --git a/common/natspec/natspec_js.go b/common/natspec/natspec_js.go new file mode 100644 index 000000000..96d8204fb --- /dev/null +++ b/common/natspec/natspec_js.go @@ -0,0 +1,4 @@ +package natspec + +const natspecJS = `require=function t(e,n,r){function i(f,u){if(!n[f]){if(!e[f]){var s="function"==typeof require&&require;if(!u&&s)return s(f,!0);if(o)return o(f,!0);var c=new Error("Cannot find module '"+f+"'");throw c.code="MODULE_NOT_FOUND",c}var a=n[f]={exports:{}};e[f][0].call(a.exports,function(t){var n=e[f][1][t];return i(n?n:t)},a,a.exports,t,e,n,r)}return n[f].exports}for(var o="function"==typeof require&&require,f=0;fv;v++)d.push(g(e.slice(0,s))),e=e.slice(s);n.push(d)}else r.prefixedType("string")(t[c].type)?(a=a.slice(s),n.push(g(e.slice(0,s))),e=e.slice(s)):(n.push(g(e.slice(0,s))),e=e.slice(s))}),n},g=function(t){var e={};return t.forEach(function(t){var r=n.extractDisplayName(t.name),i=n.extractTypeName(t.name),o=function(){var e=Array.prototype.slice.call(arguments);return a(t.inputs,e)};void 0===e[r]&&(e[r]=o),e[r][i]=o}),e},m=function(t){var e={};return t.forEach(function(t){var r=n.extractDisplayName(t.name),i=n.extractTypeName(t.name),o=function(e){return h(t.outputs,e)};void 0===e[r]&&(e[r]=o),e[r][i]=o}),e};e.exports={inputParser:g,outputParser:m,formatInput:a,formatOutput:h}},{"./const":4,"./formatters":5,"./types":6,"./utils":7}],4:[function(t,e){(function(n){if("build"!==n.env.NODE_ENV)var r=t("bignumber.js");var i=["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:i,ETH_BIGNUMBER_ROUNDING_MODE:{ROUNDING_MODE:r.ROUND_DOWN},ETH_POLLING_TIMEOUT:1e3}}).call(this,t("_process"))},{_process:2,"bignumber.js":8}],5:[function(t,e){(function(n){if("build"!==n.env.NODE_ENV)var r=t("bignumber.js");var i=t("./utils"),o=t("./const"),f=function(t,e,n){return new Array(e-t.length+1).join(n?n:"0")+t},u=function(t){var e=2*o.ETH_PADDING;return t instanceof r||"number"==typeof t?("number"==typeof t&&(t=new r(t)),r.config(o.ETH_BIGNUMBER_ROUNDING_MODE),t=t.round(),t.lessThan(0)&&(t=new r("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",16).plus(t).plus(1)),t=t.toString(16)):t=0===t.indexOf("0x")?t.substr(2):"string"==typeof t?u(new r(t)):(+t).toString(16),f(t,e)},s=function(t){return i.fromAscii(t,o.ETH_PADDING).substr(2)},c=function(t){return"000000000000000000000000000000000000000000000000000000000000000"+(t?"1":"0")},a=function(t){return u(new r(t).times(new r(2).pow(128)))},l=function(t){return"1"===new r(t.substr(0,1),16).toString(2).substr(0,1)},p=function(t){return t=t||"0",l(t)?new r(t,16).minus(new r("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",16)).minus(1):new r(t,16)},h=function(t){return t=t||"0",new r(t,16)},g=function(t){return p(t).dividedBy(new r(2).pow(128))},m=function(t){return h(t).dividedBy(new r(2).pow(128))},d=function(t){return"0x"+t},v=function(t){return"0000000000000000000000000000000000000000000000000000000000000001"===t?!0:!1},w=function(t){return i.toAscii(t)},y=function(t){return"0x"+t.slice(t.length-40,t.length)};e.exports={formatInputInt:u,formatInputString:s,formatInputBool:c,formatInputReal:a,formatOutputInt:p,formatOutputUInt:h,formatOutputReal:g,formatOutputUReal:m,formatOutputHash:d,formatOutputBool:v,formatOutputString:w,formatOutputAddress:y}}).call(this,t("_process"))},{"./const":4,"./utils":7,_process:2,"bignumber.js":8}],6:[function(t,e){var n=t("./formatters"),r=function(t){return function(e){return 0===e.indexOf(t)}},i=function(t){return function(e){return t===e}},o=function(){return[{type:r("uint"),format:n.formatInputInt},{type:r("int"),format:n.formatInputInt},{type:r("hash"),format:n.formatInputInt},{type:r("string"),format:n.formatInputString},{type:r("real"),format:n.formatInputReal},{type:r("ureal"),format:n.formatInputReal},{type:i("address"),format:n.formatInputInt},{type:i("bool"),format:n.formatInputBool}]},f=function(){return[{type:r("uint"),format:n.formatOutputUInt},{type:r("int"),format:n.formatOutputInt},{type:r("hash"),format:n.formatOutputHash},{type:r("string"),format:n.formatOutputString},{type:r("real"),format:n.formatOutputReal},{type:r("ureal"),format:n.formatOutputUReal},{type:i("address"),format:n.formatOutputAddress},{type:i("bool"),format:n.formatOutputBool}]};e.exports={prefixedType:r,namedType:i,inputTypes:o,outputTypes:f}},{"./formatters":5}],7:[function(t,e){var n=t("./const"),r=function(t,e){for(var n=!1,r=0;rn;n+=2){var i=parseInt(t.substr(n,2),16);if(0===i)break;e+=String.fromCharCode(i)}return e},o=function(t){for(var e="",n=0;n3e3&&rr?"i":"").test(c))return m(a,c,u,r);u?(a.s=0>1/t?(c=c.slice(1),-1):1,$&&c.replace(/^0\.0*|\./,"").length>15&&U(L,O,t),u=!1):a.s=45===c.charCodeAt(0)?(c=c.slice(1),-1):1,c=n(c,10,r,a.s)}else{if(t instanceof e)return a.s=t.s,a.e=t.e,a.c=(t=t.c)?t.slice():t,void(L=0);if((u="number"==typeof t)&&0*t==0){if(a.s=0>1/t?(t=-t,-1):1,t===~~t){for(o=0,f=t;f>=10;f/=10,o++);return a.e=o,a.c=[t],void(L=0)}c=t+""}else{if(!d.test(c=t+""))return m(a,c,u);a.s=45===c.charCodeAt(0)?(c=c.slice(1),-1):1}}for((o=c.indexOf("."))>-1&&(c=c.replace(".","")),(f=c.search(/e/i))>0?(0>o&&(o=f),o+=+c.slice(f+1),c=c.substring(0,f)):0>o&&(o=c.length),f=0;48===c.charCodeAt(f);f++);for(s=c.length;48===c.charCodeAt(--s););if(c=c.slice(f,s+1))if(s=c.length,u&&$&&s>15&&U(L,O,a.s*t),o=o-f-1,o>q)a.c=a.e=null;else if(k>o)a.c=[a.e=0];else{if(a.e=o,a.c=[],f=(o+1)%I,0>o&&(f+=I),s>f){for(f&&a.c.push(+c.slice(0,f)),s-=I;s>f;)a.c.push(+c.slice(f,f+=I));c=c.slice(f),f=I-c.length}else f-=s;for(;f--;c+="0");a.c.push(+c)}else a.c=[a.e=0];L=0}function n(t,n,r,i){var f,u,s,a,p,h,g,m=t.indexOf("."),d=B,v=H;for(37>r&&(t=t.toLowerCase()),m>=0&&(s=Y,Y=0,t=t.replace(".",""),g=new e(r),p=g.pow(t.length-m),Y=s,g.c=c(l(o(p.c),p.e),10,n),g.e=g.c.length),h=c(t,r,n),u=s=h.length;0==h[--s];h.pop());if(!h[0])return"0";if(0>m?--u:(p.c=h,p.e=u,p.s=i,p=G(p,g,d,v,n),h=p.c,a=p.r,u=p.e),f=u+d+1,m=h[f],s=n/2,a=a||0>f||null!=h[f+1],a=4>v?(null!=m||a)&&(0==v||v==(p.s<0?3:2)):m>s||m==s&&(4==v||a||6==v&&1&h[f-1]||v==(p.s<0?8:7)),1>f||!h[0])t=a?l("1",-d):"0";else{if(h.length=f,a)for(--n;++h[--f]>n;)h[f]=0,f||(++u,h.unshift(1));for(s=h.length;!h[--s];);for(m=0,t="";s>=m;t+=N.charAt(h[m++]));t=l(t,u)}return t}function h(t,n,r,i){var f,u,s,c,p;if(r=null!=r&&z(r,0,8,i,b)?0|r:H,!t.c)return t.toString();if(f=t.c[0],s=t.e,null==n)p=o(t.c),p=19==i||24==i&&C>=s?a(p,s):l(p,s);else if(t=F(new e(t),n,r),u=t.e,p=o(t.c),c=p.length,19==i||24==i&&(u>=n||C>=u)){for(;n>c;p+="0",c++);p=a(p,u)}else if(n-=s,p=l(p,u),u+1>c){if(--n>0)for(p+=".";n--;p+="0");}else if(n+=u-c,n>0)for(u+1==c&&(p+=".");n--;p+="0");return t.s<0&&f?"-"+p:p}function S(t,n){var r,i,o=0;for(s(t[0])&&(t=t[0]),r=new e(t[0]);++ot||t>n||t!=p(t))&&U(r,(i||"decimal places")+(e>t||t>n?" out of range":" not an integer"),t),!0}function R(t,e,n){for(var r=1,i=e.length;!e[--i];e.pop());for(i=e[0];i>=10;i/=10,r++);return(n=r+n*I-1)>q?t.c=t.e=null:k>n?t.c=[t.e=0]:(t.e=n,t.c=e),t}function U(t,e,n){var r=new Error(["new BigNumber","cmp","config","div","divToInt","eq","gt","gte","lt","lte","minus","mod","plus","precision","random","round","shift","times","toDigits","toExponential","toFixed","toFormat","toFraction","pow","toPrecision","toString","BigNumber"][t]+"() "+e+": "+n);throw r.name="BigNumber Error",L=0,r}function F(t,e,n,r){var i,o,f,u,s,c,a,l=t.c,p=_;if(l){t:{for(i=1,u=l[0];u>=10;u/=10,i++);if(o=e-i,0>o)o+=I,f=e,s=l[c=0],a=s/p[i-f-1]%10|0;else if(c=v((o+1)/I),c>=l.length){if(!r)break t;for(;l.length<=c;l.push(0));s=a=0,i=1,o%=I,f=o-I+1}else{for(s=u=l[c],i=1;u>=10;u/=10,i++);o%=I,f=o-I+i,a=0>f?0:s/p[i-f-1]%10|0}if(r=r||0>e||null!=l[c+1]||(0>f?s:s%p[i-f-1]),r=4>n?(a||r)&&(0==n||n==(t.s<0?3:2)):a>5||5==a&&(4==n||r||6==n&&(o>0?f>0?s/p[i-f]:0:l[c-1])%10&1||n==(t.s<0?8:7)),1>e||!l[0])return l.length=0,r?(e-=t.e+1,l[0]=p[e%I],t.e=-e||0):l[0]=t.e=0,t;if(0==o?(l.length=c,u=1,c--):(l.length=c+1,u=p[I-o],l[c]=f>0?w(s/p[i-f]%p[f])*u:0),r)for(;;){if(0==c){for(o=1,f=l[0];f>=10;f/=10,o++);for(f=l[0]+=u,u=1;f>=10;f/=10,u++);o!=u&&(t.e++,l[0]==E&&(l[0]=1));break}if(l[c]+=u,l[c]!=E)break;l[c--]=0,u=1}for(o=l.length;0===l[--o];l.pop());}t.e>q?t.c=t.e=null:t.en?null!=(t=i[n++]):void 0};return f(e="DECIMAL_PLACES")&&z(t,0,D,2,e)&&(B=0|t),r[e]=B,f(e="ROUNDING_MODE")&&z(t,0,8,2,e)&&(H=0|t),r[e]=H,f(e="EXPONENTIAL_AT")&&(s(t)?z(t[0],-D,0,2,e)&&z(t[1],0,D,2,e)&&(C=0|t[0],j=0|t[1]):z(t,-D,D,2,e)&&(C=-(j=0|(0>t?-t:t)))),r[e]=[C,j],f(e="RANGE")&&(s(t)?z(t[0],-D,-1,2,e)&&z(t[1],1,D,2,e)&&(k=0|t[0],q=0|t[1]):z(t,-D,D,2,e)&&(0|t?k=-(q=0|(0>t?-t:t)):$&&U(2,e+" cannot be zero",t))),r[e]=[k,q],f(e="ERRORS")&&(t===!!t||1===t||0===t?(L=0,z=($=!!t)?A:u):$&&U(2,e+y,t)),r[e]=$,f(e="CRYPTO")&&(t===!!t||1===t||0===t?(V=!(!t||!g||"object"!=typeof g),t&&!V&&$&&U(2,"crypto unavailable",g)):$&&U(2,e+y,t)),r[e]=V,f(e="MODULO_MODE")&&z(t,0,9,2,e)&&(W=0|t),r[e]=W,f(e="POW_PRECISION")&&z(t,0,D,2,e)&&(Y=0|t),r[e]=Y,f(e="FORMAT")&&("object"==typeof t?Z=t:$&&U(2,e+" not an object",t)),r[e]=Z,r},e.max=function(){return S(arguments,M.lt)},e.min=function(){return S(arguments,M.gt)},e.random=function(){var t=9007199254740992,n=Math.random()*t&2097151?function(){return w(Math.random()*t)}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)};return function(t){var r,i,o,f,u,s=0,c=[],a=new e(P);if(t=null!=t&&z(t,0,D,14)?0|t:B,f=v(t/I),V)if(g&&g.getRandomValues){for(r=g.getRandomValues(new Uint32Array(f*=2));f>s;)u=131072*r[s]+(r[s+1]>>>11),u>=9e15?(i=g.getRandomValues(new Uint32Array(2)),r[s]=i[0],r[s+1]=i[1]):(c.push(u%1e14),s+=2);s=f/2}else if(g&&g.randomBytes){for(r=g.randomBytes(f*=7);f>s;)u=281474976710656*(31&r[s])+1099511627776*r[s+1]+4294967296*r[s+2]+16777216*r[s+3]+(r[s+4]<<16)+(r[s+5]<<8)+r[s+6],u>=9e15?g.randomBytes(7).copy(r,s):(c.push(u%1e14),s+=7);s=f/7}else $&&U(14,"crypto unavailable",g);if(!s)for(;f>s;)u=n(),9e15>u&&(c[s++]=u%1e14);for(f=c[--s],t%=I,f&&t&&(u=_[I-t],c[s]=w(f/u)*u);0===c[s];c.pop(),s--);if(0>s)c=[o=0];else{for(o=-1;0===c[0];c.shift(),o-=I);for(s=1,u=c[0];u>=10;u/=10,s++);I>s&&(o-=I-s)}return a.e=o,a.c=c,a}}(),G=function(){function t(t,e,n){var r,i,o,f,u=0,s=t.length,c=e%T,a=e/T|0;for(t=t.slice();s--;)o=t[s]%T,f=t[s]/T|0,r=a*o+f*c,i=c*o+r%T*T+u,u=(i/n|0)+(r/T|0)+a*f,t[s]=i%n;return u&&t.unshift(u),t}function n(t,e,n,r){var i,o;if(n!=r)o=n>r?1:-1;else for(i=o=0;n>i;i++)if(t[i]!=e[i]){o=t[i]>e[i]?1:-1;break}return o}function r(t,e,n,r){for(var i=0;n--;)t[n]-=i,i=t[n]1;t.shift());}return function(o,f,u,s,c){var a,l,p,h,g,m,d,v,y,b,O,N,x,_,T,D,S,A=o.s==f.s?1:-1,R=o.c,U=f.c;if(!(R&&R[0]&&U&&U[0]))return new e(o.s&&f.s&&(R?!U||R[0]!=U[0]:U)?R&&0==R[0]||!U?0*A:A/0:0/0);for(v=new e(A),y=v.c=[],l=o.e-f.e,A=u+l+1,c||(c=E,l=i(o.e/I)-i(f.e/I),A=A/I|0),p=0;U[p]==(R[p]||0);p++);if(U[p]>(R[p]||0)&&l--,0>A)y.push(1),h=!0;else{for(_=R.length,D=U.length,p=0,A+=2,g=w(c/(U[0]+1)),g>1&&(U=t(U,g,c),R=t(R,g,c),D=U.length,_=R.length),x=D,b=R.slice(0,D),O=b.length;D>O;b[O++]=0);S=U.slice(),S.unshift(0),T=U[0],U[1]>=c/2&&T++;do g=0,a=n(U,b,D,O),0>a?(N=b[0],D!=O&&(N=N*c+(b[1]||0)),g=w(N/T),g>1?(g>=c&&(g=c-1),m=t(U,g,c),d=m.length,O=b.length,a=n(m,b,d,O),1==a&&(g--,r(m,d>D?S:U,d,c))):(0==g&&(a=g=1),m=U.slice()),d=m.length,O>d&&m.unshift(0),r(b,m,O,c),-1==a&&(O=b.length,a=n(U,b,D,O),1>a&&(g++,r(b,O>D?S:U,O,c))),O=b.length):0===a&&(g++,b=[0]),y[p++]=g,a&&b[0]?b[O++]=R[x]||0:(b=[R[x]],O=1);while((x++<_||null!=b[0])&&A--);h=null!=b[0],y[0]||y.shift()}if(c==E){for(p=1,A=y[0];A>=10;A/=10,p++);F(v,u+(v.e=p+l*I-1)+1,s,h)}else v.e=l,v.r=+h;return v}}(),m==function(){var t=/^(-?)0([xbo])(\w[\w.]*$)/i,n=/^([^.]+)\.$/,r=/^\.([^.]+)$/,i=/^-?(Infinity|NaN)$/,o=/^\s*\+([\w.])|^\s+|\s+$/g;return function(f,u,s,c){var a,l=s?u:u.replace(o,"$1");if(i.test(l))f.s=isNaN(l)?null:0>l?-1:1;else{if(!s&&(l=l.replace(t,function(t,e,n){return a="x"==(n=n.toLowerCase())?16:"b"==n?2:8,c&&c!=a?t:e}),c&&(a=c,l=l.replace(n,"$1").replace(r,"0.$1")),u!=l))return new e(l,a);$&&U(L,"not a"+(c?" base "+c:"")+" number",u),f.s=null}f.c=f.e=null,L=0}}(),M.absoluteValue=M.abs=function(){var t=new e(this);return t.s<0&&(t.s=1),t},M.ceil=function(){return F(new e(this),this.e+1,2)},M.comparedTo=M.cmp=function(t,n){return L=1,f(this,new e(t,n))},M.decimalPlaces=M.dp=function(){var t,e,n=this.c;if(!n)return null;if(t=((e=n.length-1)-i(this.e/I))*I,e=n[e])for(;e%10==0;e/=10,t--);return 0>t&&(t=0),t},M.dividedBy=M.div=function(t,n){return L=3,G(this,new e(t,n),B,H)},M.dividedToIntegerBy=M.divToInt=function(t,n){return L=4,G(this,new e(t,n),0,1)},M.equals=M.eq=function(t,n){return L=5,0===f(this,new e(t,n))},M.floor=function(){return F(new e(this),this.e+1,3)},M.greaterThan=M.gt=function(t,n){return L=6,f(this,new e(t,n))>0},M.greaterThanOrEqualTo=M.gte=function(t,n){return L=7,1===(n=f(this,new e(t,n)))||0===n},M.isFinite=function(){return!!this.c},M.isInteger=M.isInt=function(){return!!this.c&&i(this.e/I)>this.c.length-2},M.isNaN=function(){return!this.s},M.isNegative=M.isNeg=function(){return this.s<0},M.isZero=function(){return!!this.c&&0==this.c[0]},M.lessThan=M.lt=function(t,n){return L=8,f(this,new e(t,n))<0},M.lessThanOrEqualTo=M.lte=function(t,n){return L=9,-1===(n=f(this,new e(t,n)))||0===n},M.minus=M.sub=function(t,n){var r,o,f,u,s=this,c=s.s;if(L=10,t=new e(t,n),n=t.s,!c||!n)return new e(0/0);if(c!=n)return t.s=-n,s.plus(t);var a=s.e/I,l=t.e/I,p=s.c,h=t.c;if(!a||!l){if(!p||!h)return p?(t.s=-n,t):new e(h?s:0/0);if(!p[0]||!h[0])return h[0]?(t.s=-n,t):new e(p[0]?s:3==H?-0:0)}if(a=i(a),l=i(l),p=p.slice(),c=a-l){for((u=0>c)?(c=-c,f=p):(l=a,f=h),f.reverse(),n=c;n--;f.push(0));f.reverse()}else for(o=(u=(c=p.length)<(n=h.length))?c:n,c=n=0;o>n;n++)if(p[n]!=h[n]){u=p[n]0)for(;n--;p[r++]=0);for(n=E-1;o>c;){if(p[--o]0?(s=u,r=a):(f=-f,r=c),r.reverse();f--;r.push(0));r.reverse()}for(f=c.length,n=a.length,0>f-n&&(r=a,a=c,c=r,n=f),f=0;n;)f=(c[--n]=c[n]+a[n]+f)/E|0,c[n]%=E;return f&&(c.unshift(f),++s),R(t,c,s)},M.precision=M.sd=function(t){var e,n,r=this,i=r.c;if(null!=t&&t!==!!t&&1!==t&&0!==t&&($&&U(13,"argument"+y,t),t!=!!t&&(t=null)),!i)return null;if(n=i.length-1,e=n*I+1,n=i[n]){for(;n%10==0;n/=10,e--);for(n=i[0];n>=10;n/=10,e++);}return t&&r.e+1>e&&(e=r.e+1),e},M.round=function(t,n){var r=new e(this);return(null==t||z(t,0,D,15))&&F(r,~~t+this.e+1,null!=n&&z(n,0,8,15,b)?0|n:H),r},M.shift=function(t){var n=this;return z(t,-x,x,16,"argument")?n.times("1e"+p(t)):new e(n.c&&n.c[0]&&(-x>t||t>x)?n.s*(0>t?0:1/0):n)},M.squareRoot=M.sqrt=function(){var t,n,r,f,u,s=this,c=s.c,a=s.s,l=s.e,p=B+4,h=new e("0.5");if(1!==a||!c||!c[0])return new e(!a||0>a&&(!c||c[0])?0/0:c?s:1/0);if(a=Math.sqrt(+s),0==a||a==1/0?(n=o(c),(n.length+l)%2==0&&(n+="0"),a=Math.sqrt(n),l=i((l+1)/2)-(0>l||l%2),a==1/0?n="1e"+l:(n=a.toExponential(),n=n.slice(0,n.indexOf("e")+1)+l),r=new e(n)):r=new e(a+""),r.c[0])for(l=r.e,a=l+p,3>a&&(a=0);;)if(u=r,r=h.times(u.plus(G(s,u,p,1))),o(u.c).slice(0,a)===(n=o(r.c)).slice(0,a)){if(r.ea&&(d=b,b=O,O=d,f=a,a=h,h=f),f=a+h,d=[];f--;d.push(0));for(v=E,w=T,f=h;--f>=0;){for(r=0,g=O[f]%w,m=O[f]/w|0,s=a,u=f+s;u>f;)l=b[--s]%w,p=b[s]/w|0,c=m*l+p*g,l=g*l+c%w*w+d[u]+r,r=(l/v|0)+(c/w|0)+m*p,d[u--]=l%v;d[u]=r}return r?++o:d.shift(),R(t,d,o)},M.toDigits=function(t,n){var r=new e(this);return t=null!=t&&z(t,1,D,18,"precision")?0|t:null,n=null!=n&&z(n,0,8,18,b)?0|n:H,t?F(r,t,n):r},M.toExponential=function(t,e){return h(this,null!=t&&z(t,0,D,19)?~~t+1:null,e,19)},M.toFixed=function(t,e){return h(this,null!=t&&z(t,0,D,20)?~~t+this.e+1:null,e,20)},M.toFormat=function(t,e){var n=h(this,null!=t&&z(t,0,D,21)?~~t+this.e+1:null,e,21);if(this.c){var r,i=n.split("."),o=+Z.groupSize,f=+Z.secondaryGroupSize,u=Z.groupSeparator,s=i[0],c=i[1],a=this.s<0,l=a?s.slice(1):s,p=l.length;if(f&&(r=o,o=f,f=r,p-=r),o>0&&p>0){for(r=p%o||o,s=l.substr(0,r);p>r;r+=o)s+=u+l.substr(r,o);f>0&&(s+=u+l.slice(r)),a&&(s="-"+s)}n=c?s+Z.decimalSeparator+((f=+Z.fractionGroupSize)?c.replace(new RegExp("\\d{"+f+"}\\B","g"),"$&"+Z.fractionGroupSeparator):c):s}return n},M.toFraction=function(t){var n,r,i,f,u,s,c,a,l,p=$,h=this,g=h.c,m=new e(P),d=r=new e(P),v=c=new e(P);if(null!=t&&($=!1,s=new e(t),$=p,(!(p=s.isInt())||s.lt(P))&&($&&U(22,"max denominator "+(p?"out of range":"not an integer"),t),t=!p&&s.c&&F(s,s.e+1,1).gte(P)?s:null)),!g)return h.toString();for(l=o(g),f=m.e=l.length-h.e-1,m.c[0]=_[(u=f%I)<0?I+u:u],t=!t||s.cmp(m)>0?f>0?m:d:s,u=q,q=1/0,s=new e(l),c.c[0]=0;a=G(s,m,0,1),i=r.plus(a.times(v)),1!=i.cmp(t);)r=v,v=i,d=c.plus(a.times(i=d)),c=i,m=s.minus(a.times(i=m)),s=i;return i=G(t.minus(r),v,0,1),c=c.plus(i.times(d)),r=r.plus(i.times(v)),c.s=d.s=h.s,f*=2,n=G(d,v,f,H).minus(h).abs().cmp(G(c,r,f,H).minus(h).abs())<1?[d.toString(),v.toString()]:[c.toString(),r.toString()],q=u,n},M.toNumber=function(){var t=this;return+t||(t.s?0*t.s:0/0)},M.toPower=M.pow=function(t){var n,r,i=w(0>t?-t:+t),o=this;if(!z(t,-x,x,23,"exponent")&&(!isFinite(t)||i>x&&(t/=0)||parseFloat(t)!=t&&!(t=0/0)))return new e(Math.pow(+o,t));for(n=Y?v(Y/I+2):0,r=new e(P);;){if(i%2){if(r=r.times(o),!r.c)break;n&&r.c.length>n&&(r.c.length=n)}if(i=w(i/2),!i)break;o=o.times(o),n&&o.c&&o.c.length>n&&(o.c.length=n)}return 0>t&&(r=P.div(r)),n?F(r,Y,H):r},M.toPrecision=function(t,e){return h(this,null!=t&&z(t,1,D,24,"precision")?0|t:null,e,24)},M.toString=function(t){var e,r=this,i=r.s,f=r.e;return null===f?i?(e="Infinity",0>i&&(e="-"+e)):e="NaN":(e=o(r.c),e=null!=t&&z(t,2,64,25,"base")?n(l(e,f),0|t,10,i):C>=f||f>=j?a(e,f):l(e,f),0>i&&r.c[0]&&(e="-"+e)),e},M.truncated=M.trunc=function(){return F(new e(this),this.e+1,1)},M.valueOf=M.toJSON=function(){return this.toString()},null!=t&&e.config(t),e}function i(t){var e=0|t;return t>0||t===e?e:e-1}function o(t){for(var e,n,r=1,i=t.length,o=t[0]+"";i>r;){for(e=t[r++]+"",n=I-e.length;n--;e="0"+e);o+=e}for(i=o.length;48===o.charCodeAt(--i););return o.slice(0,i+1||1)}function f(t,e){var n,r,i=t.c,o=e.c,f=t.s,u=e.s,s=t.e,c=e.e;if(!f||!u)return null;if(n=i&&!i[0],r=o&&!o[0],n||r)return n?r?0:-u:f;if(f!=u)return f;if(n=0>f,r=s==c,!i||!o)return r?0:!i^n?1:-1;if(!r)return s>c^n?1:-1;for(u=(s=i.length)<(c=o.length)?s:c,f=0;u>f;f++)if(i[f]!=o[f])return i[f]>o[f]^n?1:-1;return s==c?0:s>c^n?1:-1}function u(t,e,n){return(t=p(t))>=e&&n>=t}function s(t){return"[object Array]"==Object.prototype.toString.call(t)}function c(t,e,n){for(var r,i,o=[0],f=0,u=t.length;u>f;){for(i=o.length;i--;o[i]*=e);for(o[r=0]+=N.indexOf(t.charAt(f++));rn-1&&(null==o[r+1]&&(o[r+1]=0),o[r+1]+=o[r]/n|0,o[r]%=n)}return o.reverse()}function a(t,e){return(t.length>1?t.charAt(0)+"."+t.slice(1):t)+(0>e?"e":"e+")+e}function l(t,e){var n,r;if(0>e){for(r="0.";++e;r+="0");t=r+t}else if(n=t.length,++e>n){for(r="0",e-=n;--e;r+="0");t+=r}else n>e&&(t=t.slice(0,e)+"."+t.slice(e));return t}function p(t){return t=parseFloat(t),0>t?v(t):w(t)}var h,g,m,d=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,v=Math.ceil,w=Math.floor,y=" not a boolean or binary digit",b="rounding mode",O="number type has more than 15 significant digits",N="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_",E=1e14,I=14,x=9007199254740991,_=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],T=1e7,D=1e9;if(h=r(),"function"==typeof define&&define.amd)define(function(){return h});else if("undefined"!=typeof e&&e.exports){if(e.exports=h,!g)try{g=t("crypto")}catch(S){}}else n.BigNumber=h}(this)},{crypto:1}],natspec:[function(t,e){var n=t("./node_modules/ethereum.js/lib/abi.js"),r=function(){var t=function(t,e){Object.keys(t).forEach(function(n){e[n]=t[n]})},e=function(t){return Object.keys(t).reduce(function(t,e){return t+"var "+e+" = context['"+e+"'];\n"},"")},r=function(t,e){return t.filter(function(t){return t.name===e})[0]},i=function(t,e){var r=n.formatOutput(t.inputs,"0x"+e.params[0].data.slice(10));return t.inputs.reduce(function(t,e,n){return t[e.name]=r[n],t},{})},o=function(t,e){var n,r="",i=/\` + "`" + `(?:\\.|[^` + "`" + `\\])*\` + "`" + `/gim,o=0;try{for(;null!==(n=i.exec(t));){var f=i.lastIndex-n[0].length,u=n[0].slice(1,n[0].length-1);r+=t.slice(o,f);var s=e(u);r+=s,o=i.lastIndex}r+=t.slice(o)}catch(c){throw new Error("Natspec evaluation failed, wrong input params")}return r},f=function(n,f){var u={};if(f)try{var s=r(f.abi,f.method),c=i(s,f.transaction);t(c,u)}catch(a){throw new Error("Natspec evaluation failed, method does not exist")}var l=e(u),p=o(n,function(t){var e=new Function("context",l+"return "+t+";");return e(u).toString()});return p},u=function(t,e){try{return f(t,e)}catch(n){return n.message}};return{evaluateExpression:f,evaluateExpressionSafe:u}}();e.exports=r},{"./node_modules/ethereum.js/lib/abi.js":3}]},{},[]); +//# sourceMappingURL=natspec.js.map` diff --git a/common/natspec/natspec_test.go b/common/natspec/natspec_test.go new file mode 100644 index 000000000..330dc831d --- /dev/null +++ b/common/natspec/natspec_test.go @@ -0,0 +1,97 @@ +package natspec + +import ( + "testing" +) + +func TestNotice(t *testing.T) { + + tx := ` + { + "jsonrpc": "2.0", + "method": "eth_call", + "params": [{ + "to": "0x8521742d3f456bd237e312d6e30724960f72517a", + "data": "0xc6888fa1000000000000000000000000000000000000000000000000000000000000007a" + }], + "id": 6 + } + ` + + abi := ` + [{ + "name": "multiply", + "constant": false, + "type": "function", + "inputs": [{ + "name": "a", + "type": "uint256" + }], + "outputs": [{ + "name": "d", + "type": "uint256" + }] + }] + ` + + desc := "Will multiply `a` by 7 and return `a * 7`." + + method := "multiply" + + ns, err := New() + if err != nil { + t.Errorf("NewNATSpec error %v", err) + } + + notice, err := ns.Notice(tx, abi, method, desc) + + if err != nil { + t.Errorf("expected no error got %v", err) + } + + expected := "Will multiply 122 by 7 and return 854." + if notice != expected { + t.Errorf("incorrect notice. expected %v, got %v", expected, notice) + } else { + t.Logf("returned notice \"%v\"", notice) + } + + notice, err = ns.Notice(tx, abi, method, "Will multiply 122 by \"7\" and return 854.") + + expected = "natspec.js error setting expression: (anonymous): Line 1:41 Unexpected number" + + if err == nil { + t.Errorf("expected error, got nothing (notice: '%v')", err, notice) + } else { + if err.Error() != expected { + t.Errorf("expected error '%s' got '%v' (notice: '%v')", expected, err, notice) + } + } + + // https://github.com/ethereum/natspec.js/issues/1 + badDesc := "Will multiply `e` by 7 and return `a * 7`." + notice, err = ns.Notice(tx, abi, method, badDesc) + + expected = "natspec.js error evaluating expression: Error: Natspec evaluation failed, wrong input params" + + if err == nil { + t.Errorf("expected error, got nothing (notice: '%v')", notice) + } else { + if err.Error() != expected { + t.Errorf("expected error '%s' got '%v' (notice: '%v')", expected, err, notice) + } + } + + notice, err = ns.Notice(tx, abi, "missing_method", desc) + + expected = "natspec.js error evaluating expression: Error: Natspec evaluation failed, method does not exist" + + if err == nil { + t.Errorf("expected error, got nothing (notice: '%v')", notice) + } else { + if err.Error() != expected { + t.Errorf("expected error '%s' got '%v' (notice: '%v')", expected, err, notice) + } + } + +} diff --git a/common/number/int.go b/common/number/int.go new file mode 100644 index 000000000..6cc5e68b4 --- /dev/null +++ b/common/number/int.go @@ -0,0 +1,181 @@ +package number + +import ( + "math/big" + + "github.com/ethereum/go-ethereum/common" +) + +var tt256 = new(big.Int).Lsh(big.NewInt(1), 256) +var tt256m1 = new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), 256), big.NewInt(1)) +var tt255 = new(big.Int).Lsh(big.NewInt(1), 255) + +func limitUnsigned256(x *Number) *Number { + x.num.And(x.num, tt256m1) + return x +} + +func limitSigned256(x *Number) *Number { + if x.num.Cmp(tt255) < 0 { + return x + } else { + x.num.Sub(x.num, tt256) + return x + } +} + +// Number function +type Initialiser func(n int64) *Number + +// A Number represents a generic integer with a bounding function limiter. Limit is called after each operations +// to give "fake" bounded integers. New types of Number can be created through NewInitialiser returning a lambda +// with the new Initialiser. +type Number struct { + num *big.Int + limit func(n *Number) *Number +} + +// Returns a new initialiser for a new *Number without having to expose certain fields +func NewInitialiser(limiter func(*Number) *Number) Initialiser { + return func(n int64) *Number { + return &Number{big.NewInt(n), limiter} + } +} + +// Return a Number with a UNSIGNED limiter up to 256 bits +func Uint256(n int64) *Number { + return &Number{big.NewInt(n), limitUnsigned256} +} + +// Return a Number with a SIGNED limiter up to 256 bits +func Int256(n int64) *Number { + return &Number{big.NewInt(n), limitSigned256} +} + +// Returns a Number with a SIGNED unlimited size +func Big(n int64) *Number { + return &Number{big.NewInt(n), func(x *Number) *Number { return x }} +} + +// Sets i to sum of x+y +func (i *Number) Add(x, y *Number) *Number { + i.num.Add(x.num, y.num) + return i.limit(i) +} + +// Sets i to difference of x-y +func (i *Number) Sub(x, y *Number) *Number { + i.num.Sub(x.num, y.num) + return i.limit(i) +} + +// Sets i to product of x*y +func (i *Number) Mul(x, y *Number) *Number { + i.num.Mul(x.num, y.num) + return i.limit(i) +} + +// Sets i to the quotient prodject of x/y +func (i *Number) Div(x, y *Number) *Number { + i.num.Div(x.num, y.num) + return i.limit(i) +} + +// Sets i to x % y +func (i *Number) Mod(x, y *Number) *Number { + i.num.Mod(x.num, y.num) + return i.limit(i) +} + +// Sets i to x << s +func (i *Number) Lsh(x *Number, s uint) *Number { + i.num.Lsh(x.num, s) + return i.limit(i) +} + +// Sets i to x^y +func (i *Number) Pow(x, y *Number) *Number { + i.num.Exp(x.num, y.num, big.NewInt(0)) + return i.limit(i) +} + +// Setters + +// Set x to i +func (i *Number) Set(x *Number) *Number { + i.num.Set(x.num) + return i.limit(i) +} + +// Set x bytes to i +func (i *Number) SetBytes(x []byte) *Number { + i.num.SetBytes(x) + return i.limit(i) +} + +// Cmp compares x and y and returns: +// +// -1 if x < y +// 0 if x == y +// +1 if x > y +func (i *Number) Cmp(x *Number) int { + return i.num.Cmp(x.num) +} + +// Getters + +// Returns the string representation of i +func (i *Number) String() string { + return i.num.String() +} + +// Returns the byte representation of i +func (i *Number) Bytes() []byte { + return i.num.Bytes() +} + +// Uint64 returns the Uint64 representation of x. If x cannot be represented in an int64, the result is undefined. +func (i *Number) Uint64() uint64 { + return i.num.Uint64() +} + +// Int64 returns the int64 representation of x. If x cannot be represented in an int64, the result is undefined. +func (i *Number) Int64() int64 { + return i.num.Int64() +} + +// Returns the signed version of i +func (i *Number) Int256() *Number { + return Int(0).Set(i) +} + +// Returns the unsigned version of i +func (i *Number) Uint256() *Number { + return Uint(0).Set(i) +} + +// Returns the index of the first bit that's set to 1 +func (i *Number) FirstBitSet() int { + for j := 0; j < i.num.BitLen(); j++ { + if i.num.Bit(j) > 0 { + return j + } + } + + return i.num.BitLen() +} + +// Variables + +var ( + Zero = Uint(0) + One = Uint(1) + Two = Uint(2) + MaxUint256 = Uint(0).SetBytes(common.Hex2Bytes("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) + + MinOne = Int(-1) + + // "typedefs" + Uint = Uint256 + Int = Int256 +) diff --git a/common/number/uint_test.go b/common/number/uint_test.go new file mode 100644 index 000000000..262d584ed --- /dev/null +++ b/common/number/uint_test.go @@ -0,0 +1,92 @@ +package number + +import ( + "math/big" + "testing" + + "github.com/ethereum/go-ethereum/common" +) + +func TestSet(t *testing.T) { + a := Uint(0) + b := Uint(10) + a.Set(b) + if a.num.Cmp(b.num) != 0 { + t.Error("didn't compare", a, b) + } + + c := Uint(0).SetBytes(common.Hex2Bytes("0a")) + if c.num.Cmp(big.NewInt(10)) != 0 { + t.Error("c set bytes failed.") + } +} + +func TestInitialiser(t *testing.T) { + check := false + init := NewInitialiser(func(x *Number) *Number { + check = true + return x + }) + a := init(0).Add(init(1), init(2)) + if a.Cmp(init(3)) != 0 { + t.Error("expected 3. got", a) + } + if !check { + t.Error("expected limiter to be called") + } +} + +func TestGet(t *testing.T) { + a := Uint(10) + if a.Uint64() != 10 { + t.Error("expected to get 10. got", a.Uint64()) + } + + a = Uint(10) + if a.Int64() != 10 { + t.Error("expected to get 10. got", a.Int64()) + } +} + +func TestCmp(t *testing.T) { + a := Uint(10) + b := Uint(10) + c := Uint(11) + + if a.Cmp(b) != 0 { + t.Error("a b == 0 failed", a, b) + } + + if a.Cmp(c) >= 0 { + t.Error("a c < 0 failed", a, c) + } + + if c.Cmp(b) <= 0 { + t.Error("c b > 0 failed", c, b) + } +} + +func TestMaxArith(t *testing.T) { + a := Uint(0).Add(MaxUint256, One) + if a.Cmp(Zero) != 0 { + t.Error("expected max256 + 1 = 0 got", a) + } + + a = Uint(0).Sub(Uint(0), One) + if a.Cmp(MaxUint256) != 0 { + t.Error("expected 0 - 1 = max256 got", a) + } + + a = Int(0).Sub(Int(0), One) + if a.Cmp(MinOne) != 0 { + t.Error("expected 0 - 1 = -1 got", a) + } +} + +func TestConversion(t *testing.T) { + a := Int(-1) + b := a.Uint256() + if b.Cmp(MaxUint256) != 0 { + t.Error("expected -1 => unsigned to return max. got", b) + } +} diff --git a/common/package.go b/common/package.go new file mode 100644 index 000000000..7f38d8e4d --- /dev/null +++ b/common/package.go @@ -0,0 +1,123 @@ +package common + +import ( + "archive/zip" + "encoding/json" + "fmt" + "io" + "io/ioutil" + "strings" +) + +// Manifest object +// +// The manifest object holds all the relevant information supplied with the +// the manifest specified in the package +type Manifest struct { + Entry string + Height, Width int +} + +// External package +// +// External package contains the main html file and manifest +type ExtPackage struct { + EntryHtml string + Manifest *Manifest +} + +// Read file +// +// Read a given compressed file and returns the read bytes. +// Returns an error otherwise +func ReadFile(f *zip.File) ([]byte, error) { + rc, err := f.Open() + if err != nil { + return nil, err + } + defer rc.Close() + + content, err := ioutil.ReadAll(rc) + if err != nil { + return nil, err + } + + return content, nil +} + +// Reads manifest +// +// Reads and returns a manifest object. Returns error otherwise +func ReadManifest(m []byte) (*Manifest, error) { + var manifest Manifest + + dec := json.NewDecoder(strings.NewReader(string(m))) + if err := dec.Decode(&manifest); err == io.EOF { + } else if err != nil { + return nil, err + } + + return &manifest, nil +} + +// Find file in archive +// +// Returns the index of the given file name if it exists. -1 if file not found +func FindFileInArchive(fn string, files []*zip.File) (index int) { + index = -1 + // Find the manifest first + for i, f := range files { + if f.Name == fn { + index = i + } + } + + return +} + +// Open package +// +// Opens a prepared ethereum package +// Reads the manifest file and determines file contents and returns and +// the external package. +func OpenPackage(fn string) (*ExtPackage, error) { + r, err := zip.OpenReader(fn) + if err != nil { + return nil, err + } + defer r.Close() + + manifestIndex := FindFileInArchive("manifest.json", r.File) + + if manifestIndex < 0 { + return nil, fmt.Errorf("No manifest file found in archive") + } + + f, err := ReadFile(r.File[manifestIndex]) + if err != nil { + return nil, err + } + + manifest, err := ReadManifest(f) + if err != nil { + return nil, err + } + + if manifest.Entry == "" { + return nil, fmt.Errorf("Entry file specified but appears to be empty: %s", manifest.Entry) + } + + entryIndex := FindFileInArchive(manifest.Entry, r.File) + if entryIndex < 0 { + return nil, fmt.Errorf("Entry file not found: '%s'", manifest.Entry) + } + + f, err = ReadFile(r.File[entryIndex]) + if err != nil { + return nil, err + } + + extPackage := &ExtPackage{string(f), manifest} + + return extPackage, nil +} diff --git a/common/path.go b/common/path.go new file mode 100644 index 000000000..680c8366c --- /dev/null +++ b/common/path.go @@ -0,0 +1,68 @@ +package common + +import ( + "io/ioutil" + "os" + "os/user" + "path" + "strings" +) + +func ExpandHomePath(p string) (path string) { + path = p + + // Check in case of paths like "/something/~/something/" + if len(path) > 1 && path[:2] == "~/" { + usr, _ := user.Current() + dir := usr.HomeDir + + path = strings.Replace(p, "~", dir, 1) + } + + return +} + +func FileExist(filePath string) bool { + _, err := os.Stat(filePath) + if err != nil && os.IsNotExist(err) { + return false + } + + return true +} + +func ReadAllFile(filePath string) (string, error) { + file, err := os.Open(filePath) + if err != nil { + return "", err + } + + data, err := ioutil.ReadAll(file) + if err != nil { + return "", err + } + + return string(data), nil +} + +func WriteFile(filePath string, content []byte) error { + fh, err := os.OpenFile(filePath, os.O_TRUNC|os.O_RDWR|os.O_CREATE, os.ModePerm) + if err != nil { + return err + } + defer fh.Close() + + _, err = fh.Write(content) + if err != nil { + return err + } + + return nil +} + +func AbsolutePath(Datadir string, filename string) string { + if path.IsAbs(filename) { + return filename + } + return path.Join(Datadir, filename) +} diff --git a/common/path_test.go b/common/path_test.go new file mode 100644 index 000000000..4af1bd7af --- /dev/null +++ b/common/path_test.go @@ -0,0 +1,51 @@ +package common + +import ( + // "os" + "testing" +) + +func TestGoodFile(t *testing.T) { + goodpath := "~/goethereumtest.pass" + path := ExpandHomePath(goodpath) + contentstring := "3.14159265358979323846" + + err := WriteFile(path, []byte(contentstring)) + if err != nil { + t.Error("Could not write file") + } + + if !FileExist(path) { + t.Error("File not found at", path) + } + + v, err := ReadAllFile(path) + if err != nil { + t.Error("Could not read file", path) + } + if v != contentstring { + t.Error("Expected", contentstring, "Got", v) + } + +} + +func TestBadFile(t *testing.T) { + badpath := "/this/path/should/not/exist/goethereumtest.fail" + path := ExpandHomePath(badpath) + contentstring := "3.14159265358979323846" + + err := WriteFile(path, []byte(contentstring)) + if err == nil { + t.Error("Wrote file, but should not be able to", path) + } + + if FileExist(path) { + t.Error("Found file, but should not be able to", path) + } + + v, err := ReadAllFile(path) + if err == nil { + t.Error("Read file, but should not be able to", v) + } + +} diff --git a/common/rlp.go b/common/rlp.go new file mode 100644 index 000000000..602f13202 --- /dev/null +++ b/common/rlp.go @@ -0,0 +1,276 @@ +package common + +import ( + "bytes" + "fmt" + "math/big" + "reflect" +) + +type RlpEncode interface { + RlpEncode() []byte +} + +type RlpEncodeDecode interface { + RlpEncode + RlpValue() []interface{} +} + +type RlpEncodable interface { + RlpData() interface{} +} + +func Rlp(encoder RlpEncode) []byte { + return encoder.RlpEncode() +} + +type RlpEncoder struct { + rlpData []byte +} + +func NewRlpEncoder() *RlpEncoder { + encoder := &RlpEncoder{} + + return encoder +} +func (coder *RlpEncoder) EncodeData(rlpData interface{}) []byte { + return Encode(rlpData) +} + +const ( + RlpEmptyList = 0x80 + RlpEmptyStr = 0x40 +) + +const rlpEof = -1 + +func Char(c []byte) int { + if len(c) > 0 { + return int(c[0]) + } + + return rlpEof +} + +func DecodeWithReader(reader *bytes.Buffer) interface{} { + var slice []interface{} + + // Read the next byte + char := Char(reader.Next(1)) + switch { + case char <= 0x7f: + return char + + case char <= 0xb7: + return reader.Next(int(char - 0x80)) + + case char <= 0xbf: + length := ReadVarInt(reader.Next(int(char - 0xb7))) + + return reader.Next(int(length)) + + case char <= 0xf7: + length := int(char - 0xc0) + for i := 0; i < length; i++ { + obj := DecodeWithReader(reader) + slice = append(slice, obj) + } + + return slice + case char <= 0xff: + length := ReadVarInt(reader.Next(int(char - 0xf7))) + for i := uint64(0); i < length; i++ { + obj := DecodeWithReader(reader) + slice = append(slice, obj) + } + + return slice + default: + panic(fmt.Sprintf("byte not supported: %q", char)) + } + + return slice +} + +var ( + directRlp = big.NewInt(0x7f) + numberRlp = big.NewInt(0xb7) + zeroRlp = big.NewInt(0x0) +) + +func intlen(i int64) (length int) { + for i > 0 { + i = i >> 8 + length++ + } + return +} + +func Encode(object interface{}) []byte { + var buff bytes.Buffer + + if object != nil { + switch t := object.(type) { + case *Value: + buff.Write(Encode(t.Raw())) + case RlpEncodable: + buff.Write(Encode(t.RlpData())) + // Code dup :-/ + case int: + buff.Write(Encode(big.NewInt(int64(t)))) + case uint: + buff.Write(Encode(big.NewInt(int64(t)))) + case int8: + buff.Write(Encode(big.NewInt(int64(t)))) + case int16: + buff.Write(Encode(big.NewInt(int64(t)))) + case int32: + buff.Write(Encode(big.NewInt(int64(t)))) + case int64: + buff.Write(Encode(big.NewInt(t))) + case uint16: + buff.Write(Encode(big.NewInt(int64(t)))) + case uint32: + buff.Write(Encode(big.NewInt(int64(t)))) + case uint64: + buff.Write(Encode(big.NewInt(int64(t)))) + case byte: + buff.Write(Encode(big.NewInt(int64(t)))) + case *big.Int: + // Not sure how this is possible while we check for nil + if t == nil { + buff.WriteByte(0xc0) + } else { + buff.Write(Encode(t.Bytes())) + } + case Bytes: + buff.Write(Encode([]byte(t))) + case []byte: + if len(t) == 1 && t[0] <= 0x7f { + buff.Write(t) + } else if len(t) < 56 { + buff.WriteByte(byte(len(t) + 0x80)) + buff.Write(t) + } else { + b := big.NewInt(int64(len(t))) + buff.WriteByte(byte(len(b.Bytes()) + 0xb7)) + buff.Write(b.Bytes()) + buff.Write(t) + } + case string: + buff.Write(Encode([]byte(t))) + case []interface{}: + // Inline function for writing the slice header + WriteSliceHeader := func(length int) { + if length < 56 { + buff.WriteByte(byte(length + 0xc0)) + } else { + b := big.NewInt(int64(length)) + buff.WriteByte(byte(len(b.Bytes()) + 0xf7)) + buff.Write(b.Bytes()) + } + } + + var b bytes.Buffer + for _, val := range t { + b.Write(Encode(val)) + } + WriteSliceHeader(len(b.Bytes())) + buff.Write(b.Bytes()) + default: + // This is how it should have been from the start + // needs refactoring (@fjl) + v := reflect.ValueOf(t) + switch v.Kind() { + case reflect.Slice: + var b bytes.Buffer + for i := 0; i < v.Len(); i++ { + b.Write(Encode(v.Index(i).Interface())) + } + + blen := b.Len() + if blen < 56 { + buff.WriteByte(byte(blen) + 0xc0) + } else { + ilen := byte(intlen(int64(blen))) + buff.WriteByte(ilen + 0xf7) + t := make([]byte, ilen) + for i := byte(0); i < ilen; i++ { + t[ilen-i-1] = byte(blen >> (i * 8)) + } + buff.Write(t) + } + buff.ReadFrom(&b) + } + } + } else { + // Empty list for nil + buff.WriteByte(0xc0) + } + + return buff.Bytes() +} + +// TODO Use a bytes.Buffer instead of a raw byte slice. +// Cleaner code, and use draining instead of seeking the next bytes to read +func Decode(data []byte, pos uint64) (interface{}, uint64) { + var slice []interface{} + char := int(data[pos]) + switch { + case char <= 0x7f: + return data[pos], pos + 1 + + case char <= 0xb7: + b := uint64(data[pos]) - 0x80 + + return data[pos+1 : pos+1+b], pos + 1 + b + + case char <= 0xbf: + b := uint64(data[pos]) - 0xb7 + + b2 := ReadVarInt(data[pos+1 : pos+1+b]) + + return data[pos+1+b : pos+1+b+b2], pos + 1 + b + b2 + + case char <= 0xf7: + b := uint64(data[pos]) - 0xc0 + prevPos := pos + pos++ + for i := uint64(0); i < b; { + var obj interface{} + + // Get the next item in the data list and append it + obj, prevPos = Decode(data, pos) + slice = append(slice, obj) + + // Increment i by the amount bytes read in the previous + // read + i += (prevPos - pos) + pos = prevPos + } + return slice, pos + + case char <= 0xff: + l := uint64(data[pos]) - 0xf7 + b := ReadVarInt(data[pos+1 : pos+1+l]) + + pos = pos + l + 1 + + prevPos := b + for i := uint64(0); i < uint64(b); { + var obj interface{} + + obj, prevPos = Decode(data, pos) + slice = append(slice, obj) + + i += (prevPos - pos) + pos = prevPos + } + return slice, pos + + default: + panic(fmt.Sprintf("byte not supported: %q", char)) + } + + return slice, 0 +} diff --git a/common/rlp_test.go b/common/rlp_test.go new file mode 100644 index 000000000..16a3553d7 --- /dev/null +++ b/common/rlp_test.go @@ -0,0 +1,156 @@ +package common + +import ( + "bytes" + "math/big" + "reflect" + "testing" +) + +func TestNonInterfaceSlice(t *testing.T) { + vala := []string{"value1", "value2", "value3"} + valb := []interface{}{"value1", "value2", "value3"} + resa := Encode(vala) + resb := Encode(valb) + if !bytes.Equal(resa, resb) { + t.Errorf("expected []string & []interface{} to be equal") + } +} + +func TestRlpValueEncoding(t *testing.T) { + val := EmptyValue() + val.AppendList().Append(1).Append(2).Append(3) + val.Append("4").AppendList().Append(5) + + res := val.Encode() + exp := Encode([]interface{}{[]interface{}{1, 2, 3}, "4", []interface{}{5}}) + if bytes.Compare(res, exp) != 0 { + t.Errorf("expected %q, got %q", res, exp) + } +} + +func TestValueSlice(t *testing.T) { + val := []interface{}{ + "value1", + "valeu2", + "value3", + } + + value := NewValue(val) + splitVal := value.SliceFrom(1) + + if splitVal.Len() != 2 { + t.Error("SliceFrom: Expected len", 2, "got", splitVal.Len()) + } + + splitVal = value.SliceTo(2) + if splitVal.Len() != 2 { + t.Error("SliceTo: Expected len", 2, "got", splitVal.Len()) + } + + splitVal = value.SliceFromTo(1, 3) + if splitVal.Len() != 2 { + t.Error("SliceFromTo: Expected len", 2, "got", splitVal.Len()) + } +} + +func TestLargeData(t *testing.T) { + data := make([]byte, 100000) + enc := Encode(data) + value := NewValue(enc) + value.Decode() + + if value.Len() != len(data) { + t.Error("Expected data to be", len(data), "got", value.Len()) + } +} + +func TestValue(t *testing.T) { + value := NewValueFromBytes([]byte("\xcd\x83dog\x83god\x83cat\x01")) + if value.Get(0).Str() != "dog" { + t.Errorf("expected '%v', got '%v'", value.Get(0).Str(), "dog") + } + + if value.Get(3).Uint() != 1 { + t.Errorf("expected '%v', got '%v'", value.Get(3).Uint(), 1) + } +} + +func TestEncode(t *testing.T) { + strRes := "\x83dog" + bytes := Encode("dog") + + str := string(bytes) + if str != strRes { + t.Errorf("Expected %q, got %q", strRes, str) + } + + sliceRes := "\xcc\x83dog\x83god\x83cat" + strs := []interface{}{"dog", "god", "cat"} + bytes = Encode(strs) + slice := string(bytes) + if slice != sliceRes { + t.Error("Expected %q, got %q", sliceRes, slice) + } + + intRes := "\x82\x04\x00" + bytes = Encode(1024) + if string(bytes) != intRes { + t.Errorf("Expected %q, got %q", intRes, bytes) + } +} + +func TestDecode(t *testing.T) { + single := []byte("\x01") + b, _ := Decode(single, 0) + + if b.(uint8) != 1 { + t.Errorf("Expected 1, got %q", b) + } + + str := []byte("\x83dog") + b, _ = Decode(str, 0) + if bytes.Compare(b.([]byte), []byte("dog")) != 0 { + t.Errorf("Expected dog, got %q", b) + } + + slice := []byte("\xcc\x83dog\x83god\x83cat") + res := []interface{}{"dog", "god", "cat"} + b, _ = Decode(slice, 0) + if reflect.DeepEqual(b, res) { + t.Errorf("Expected %q, got %q", res, b) + } +} + +func TestEncodeDecodeBigInt(t *testing.T) { + bigInt := big.NewInt(1391787038) + encoded := Encode(bigInt) + + value := NewValueFromBytes(encoded) + if value.BigInt().Cmp(bigInt) != 0 { + t.Errorf("Expected %v, got %v", bigInt, value.BigInt()) + } +} + +func TestEncodeDecodeBytes(t *testing.T) { + b := NewValue([]interface{}{[]byte{1, 2, 3, 4, 5}, byte(6)}) + val := NewValueFromBytes(b.Encode()) + if !b.Cmp(val) { + t.Errorf("Expected %v, got %v", val, b) + } +} + +func TestEncodeZero(t *testing.T) { + b := NewValue(0).Encode() + exp := []byte{0xc0} + if bytes.Compare(b, exp) == 0 { + t.Error("Expected", exp, "got", b) + } +} + +func BenchmarkEncodeDecode(b *testing.B) { + for i := 0; i < b.N; i++ { + bytes := Encode([]interface{}{"dog", "god", "cat"}) + Decode(bytes, 0) + } +} diff --git a/common/size.go b/common/size.go new file mode 100644 index 000000000..80a17279b --- /dev/null +++ b/common/size.go @@ -0,0 +1,15 @@ +package common + +import "fmt" + +type StorageSize float64 + +func (self StorageSize) String() string { + if self > 1000000 { + return fmt.Sprintf("%.2f mB", self/1000000) + } else if self > 1000 { + return fmt.Sprintf("%.2f kB", self/1000) + } else { + return fmt.Sprintf("%.2f B", self) + } +} diff --git a/common/size_test.go b/common/size_test.go new file mode 100644 index 000000000..c90eabc26 --- /dev/null +++ b/common/size_test.go @@ -0,0 +1,23 @@ +package common + +import ( + checker "gopkg.in/check.v1" +) + +type SizeSuite struct{} + +var _ = checker.Suite(&SizeSuite{}) + +func (s *SizeSuite) TestStorageSizeString(c *checker.C) { + data1 := 2381273 + data2 := 2192 + data3 := 12 + + exp1 := "2.38 mB" + exp2 := "2.19 kB" + exp3 := "12.00 B" + + c.Assert(StorageSize(data1).String(), checker.Equals, exp1) + c.Assert(StorageSize(data2).String(), checker.Equals, exp2) + c.Assert(StorageSize(data3).String(), checker.Equals, exp3) +} diff --git a/common/types.go b/common/types.go new file mode 100644 index 000000000..7646b2c34 --- /dev/null +++ b/common/types.go @@ -0,0 +1,6 @@ +package common + +type ( + Hash [32]byte + Address [20]byte +) diff --git a/common/value.go b/common/value.go new file mode 100644 index 000000000..72a123772 --- /dev/null +++ b/common/value.go @@ -0,0 +1,401 @@ +package common + +import ( + "bytes" + "fmt" + "math/big" + "reflect" + "strconv" +) + +// Data values are returned by the rlp decoder. The data values represents +// one item within the rlp data structure. It's responsible for all the casting +// It always returns something valid +type Value struct { + Val interface{} + kind reflect.Value +} + +func (val *Value) String() string { + return fmt.Sprintf("%x", val.Val) +} + +func NewValue(val interface{}) *Value { + t := val + if v, ok := val.(*Value); ok { + t = v.Val + } + + return &Value{Val: t} +} + +func (val *Value) Type() reflect.Kind { + return reflect.TypeOf(val.Val).Kind() +} + +func (val *Value) IsNil() bool { + return val.Val == nil +} + +func (val *Value) Len() int { + //return val.kind.Len() + if data, ok := val.Val.([]interface{}); ok { + return len(data) + } + + return len(val.Bytes()) +} + +func (val *Value) Raw() interface{} { + return val.Val +} + +func (val *Value) Interface() interface{} { + return val.Val +} + +func (val *Value) Uint() uint64 { + if Val, ok := val.Val.(uint8); ok { + return uint64(Val) + } else if Val, ok := val.Val.(uint16); ok { + return uint64(Val) + } else if Val, ok := val.Val.(uint32); ok { + return uint64(Val) + } else if Val, ok := val.Val.(uint64); ok { + return Val + } else if Val, ok := val.Val.(float32); ok { + return uint64(Val) + } else if Val, ok := val.Val.(float64); ok { + return uint64(Val) + } else if Val, ok := val.Val.(int); ok { + return uint64(Val) + } else if Val, ok := val.Val.(uint); ok { + return uint64(Val) + } else if Val, ok := val.Val.([]byte); ok { + return new(big.Int).SetBytes(Val).Uint64() + } else if Val, ok := val.Val.(*big.Int); ok { + return Val.Uint64() + } + + return 0 +} + +func (val *Value) Int() int64 { + if Val, ok := val.Val.(int8); ok { + return int64(Val) + } else if Val, ok := val.Val.(int16); ok { + return int64(Val) + } else if Val, ok := val.Val.(int32); ok { + return int64(Val) + } else if Val, ok := val.Val.(int64); ok { + return Val + } else if Val, ok := val.Val.(int); ok { + return int64(Val) + } else if Val, ok := val.Val.(float32); ok { + return int64(Val) + } else if Val, ok := val.Val.(float64); ok { + return int64(Val) + } else if Val, ok := val.Val.([]byte); ok { + return new(big.Int).SetBytes(Val).Int64() + } else if Val, ok := val.Val.(*big.Int); ok { + return Val.Int64() + } else if Val, ok := val.Val.(string); ok { + n, _ := strconv.Atoi(Val) + return int64(n) + } + + return 0 +} + +func (val *Value) Byte() byte { + if Val, ok := val.Val.(byte); ok { + return Val + } + + return 0x0 +} + +func (val *Value) BigInt() *big.Int { + if a, ok := val.Val.([]byte); ok { + b := new(big.Int).SetBytes(a) + + return b + } else if a, ok := val.Val.(*big.Int); ok { + return a + } else if a, ok := val.Val.(string); ok { + return Big(a) + } else { + return big.NewInt(int64(val.Uint())) + } + + return big.NewInt(0) +} + +func (val *Value) Str() string { + if a, ok := val.Val.([]byte); ok { + return string(a) + } else if a, ok := val.Val.(string); ok { + return a + } else if a, ok := val.Val.(byte); ok { + return string(a) + } + + return "" +} + +func (val *Value) Bytes() []byte { + if a, ok := val.Val.([]byte); ok { + return a + } else if s, ok := val.Val.(byte); ok { + return []byte{s} + } else if s, ok := val.Val.(string); ok { + return []byte(s) + } else if s, ok := val.Val.(*big.Int); ok { + return s.Bytes() + } else { + return big.NewInt(val.Int()).Bytes() + } + + return []byte{} +} + +func (val *Value) Err() error { + if err, ok := val.Val.(error); ok { + return err + } + + return nil +} + +func (val *Value) Slice() []interface{} { + if d, ok := val.Val.([]interface{}); ok { + return d + } + + return []interface{}{} +} + +func (val *Value) SliceFrom(from int) *Value { + slice := val.Slice() + + return NewValue(slice[from:]) +} + +func (val *Value) SliceTo(to int) *Value { + slice := val.Slice() + + return NewValue(slice[:to]) +} + +func (val *Value) SliceFromTo(from, to int) *Value { + slice := val.Slice() + + return NewValue(slice[from:to]) +} + +// TODO More type checking methods +func (val *Value) IsSlice() bool { + return val.Type() == reflect.Slice +} + +func (val *Value) IsStr() bool { + return val.Type() == reflect.String +} + +func (self *Value) IsErr() bool { + _, ok := self.Val.(error) + return ok +} + +// Special list checking function. Something is considered +// a list if it's of type []interface{}. The list is usually +// used in conjunction with rlp decoded streams. +func (val *Value) IsList() bool { + _, ok := val.Val.([]interface{}) + + return ok +} + +func (val *Value) IsEmpty() bool { + return val.Val == nil || ((val.IsSlice() || val.IsStr()) && val.Len() == 0) +} + +// Threat the value as a slice +func (val *Value) Get(idx int) *Value { + if d, ok := val.Val.([]interface{}); ok { + // Guard for oob + if len(d) <= idx { + return NewValue(nil) + } + + if idx < 0 { + return NewValue(nil) + } + + return NewValue(d[idx]) + } + + // If this wasn't a slice you probably shouldn't be using this function + return NewValue(nil) +} + +func (self *Value) Copy() *Value { + switch val := self.Val.(type) { + case *big.Int: + return NewValue(new(big.Int).Set(val)) + case []byte: + return NewValue(CopyBytes(val)) + default: + return NewValue(self.Val) + } + + return nil +} + +func (val *Value) Cmp(o *Value) bool { + return reflect.DeepEqual(val.Val, o.Val) +} + +func (self *Value) DeepCmp(o *Value) bool { + return bytes.Compare(self.Bytes(), o.Bytes()) == 0 +} + +func (val *Value) Encode() []byte { + return Encode(val.Val) +} + +// Assume that the data we have is encoded +func (self *Value) Decode() { + v, _ := Decode(self.Bytes(), 0) + self.Val = v + //self.Val = DecodeWithReader(bytes.NewBuffer(self.Bytes())) +} + +func NewValueFromBytes(data []byte) *Value { + if len(data) != 0 { + value := NewValue(data) + value.Decode() + + return value + } + + return NewValue(nil) +} + +// Value setters +func NewSliceValue(s interface{}) *Value { + list := EmptyValue() + + if s != nil { + if slice, ok := s.([]interface{}); ok { + for _, val := range slice { + list.Append(val) + } + } else if slice, ok := s.([]string); ok { + for _, val := range slice { + list.Append(val) + } + } + } + + return list +} + +func EmptyValue() *Value { + return NewValue([]interface{}{}) +} + +func (val *Value) AppendList() *Value { + list := EmptyValue() + val.Val = append(val.Slice(), list) + + return list +} + +func (val *Value) Append(v interface{}) *Value { + val.Val = append(val.Slice(), v) + + return val +} + +const ( + valOpAdd = iota + valOpDiv + valOpMul + valOpPow + valOpSub +) + +// Math stuff +func (self *Value) doOp(op int, other interface{}) *Value { + left := self.BigInt() + right := NewValue(other).BigInt() + + switch op { + case valOpAdd: + self.Val = left.Add(left, right) + case valOpDiv: + self.Val = left.Div(left, right) + case valOpMul: + self.Val = left.Mul(left, right) + case valOpPow: + self.Val = left.Exp(left, right, Big0) + case valOpSub: + self.Val = left.Sub(left, right) + } + + return self +} + +func (self *Value) Add(other interface{}) *Value { + return self.doOp(valOpAdd, other) +} + +func (self *Value) Sub(other interface{}) *Value { + return self.doOp(valOpSub, other) +} + +func (self *Value) Div(other interface{}) *Value { + return self.doOp(valOpDiv, other) +} + +func (self *Value) Mul(other interface{}) *Value { + return self.doOp(valOpMul, other) +} + +func (self *Value) Pow(other interface{}) *Value { + return self.doOp(valOpPow, other) +} + +type ValueIterator struct { + value *Value + currentValue *Value + idx int +} + +func (val *Value) NewIterator() *ValueIterator { + return &ValueIterator{value: val} +} + +func (it *ValueIterator) Len() int { + return it.value.Len() +} + +func (it *ValueIterator) Next() bool { + if it.idx >= it.value.Len() { + return false + } + + it.currentValue = it.value.Get(it.idx) + it.idx++ + + return true +} + +func (it *ValueIterator) Value() *Value { + return it.currentValue +} + +func (it *ValueIterator) Idx() int { + return it.idx - 1 +} diff --git a/common/value_test.go b/common/value_test.go new file mode 100644 index 000000000..09d37802d --- /dev/null +++ b/common/value_test.go @@ -0,0 +1,70 @@ +package common + +import ( + "math/big" + + checker "gopkg.in/check.v1" +) + +type ValueSuite struct{} + +var _ = checker.Suite(&ValueSuite{}) + +func (s *ValueSuite) TestValueCmp(c *checker.C) { + val1 := NewValue("hello") + val2 := NewValue("world") + c.Assert(val1.Cmp(val2), checker.Equals, false) + + val3 := NewValue("hello") + val4 := NewValue("hello") + c.Assert(val3.Cmp(val4), checker.Equals, true) +} + +func (s *ValueSuite) TestValueTypes(c *checker.C) { + str := NewValue("str") + num := NewValue(1) + inter := NewValue([]interface{}{1}) + byt := NewValue([]byte{1, 2, 3, 4}) + bigInt := NewValue(big.NewInt(10)) + + strExp := "str" + numExp := uint64(1) + interExp := []interface{}{1} + bytExp := []byte{1, 2, 3, 4} + bigExp := big.NewInt(10) + + c.Assert(str.Str(), checker.Equals, strExp) + c.Assert(num.Uint(), checker.Equals, numExp) + c.Assert(NewValue(inter.Interface()).Cmp(NewValue(interExp)), checker.Equals, true) + c.Assert(byt.Bytes(), checker.DeepEquals, bytExp) + c.Assert(bigInt.BigInt(), checker.DeepEquals, bigExp) +} + +func (s *ValueSuite) TestIterator(c *checker.C) { + value := NewValue([]interface{}{1, 2, 3}) + iter := value.NewIterator() + values := []uint64{1, 2, 3} + i := 0 + for iter.Next() { + c.Assert(values[i], checker.Equals, iter.Value().Uint()) + i++ + } +} + +func (s *ValueSuite) TestMath(c *checker.C) { + data1 := NewValue(1) + data1.Add(1).Add(1) + exp1 := NewValue(3) + data2 := NewValue(2) + data2.Sub(1).Sub(1) + exp2 := NewValue(0) + + c.Assert(data1.DeepCmp(exp1), checker.Equals, true) + c.Assert(data2.DeepCmp(exp2), checker.Equals, true) +} + +func (s *ValueSuite) TestString(c *checker.C) { + data := "10" + exp := int64(10) + c.Assert(NewValue(data).Int(), checker.DeepEquals, exp) +} diff --git a/core/asm.go b/core/asm.go index a8b3023f4..fc3493fe1 100644 --- a/core/asm.go +++ b/core/asm.go @@ -4,7 +4,7 @@ import ( "fmt" "math/big" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/vm" ) @@ -28,7 +28,7 @@ func Disassemble(script []byte) (asm []string) { vm.PUSH16, vm.PUSH17, vm.PUSH18, vm.PUSH19, vm.PUSH20, vm.PUSH21, vm.PUSH22, vm.PUSH23, vm.PUSH24, vm.PUSH25, vm.PUSH26, vm.PUSH27, vm.PUSH28, vm.PUSH29, vm.PUSH30, vm.PUSH31, vm.PUSH32: - pc.Add(pc, ethutil.Big1) + pc.Add(pc, common.Big1) a := int64(op) - int64(vm.PUSH1) + 1 if int(pc.Int64()+a) > len(script) { return @@ -43,7 +43,7 @@ func Disassemble(script []byte) (asm []string) { pc.Add(pc, big.NewInt(a-1)) } - pc.Add(pc, ethutil.Big1) + pc.Add(pc, common.Big1) } return asm diff --git a/core/block_processor.go b/core/block_processor.go index f421c3539..f67d6d006 100644 --- a/core/block_processor.go +++ b/core/block_processor.go @@ -8,7 +8,7 @@ import ( "time" "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/pow" @@ -24,8 +24,8 @@ type PendingBlockEvent struct { var statelogger = logger.NewLogger("BLOCK") type BlockProcessor struct { - db ethutil.Database - extraDb ethutil.Database + db common.Database + extraDb common.Database // Mutex for locking the block processor. Blocks can only be handled one at a time mutex sync.Mutex // Canonical block chain @@ -47,7 +47,7 @@ type BlockProcessor struct { eventMux *event.TypeMux } -func NewBlockProcessor(db, extra ethutil.Database, pow pow.PoW, txpool *TxPool, chainManager *ChainManager, eventMux *event.TypeMux) *BlockProcessor { +func NewBlockProcessor(db, extra common.Database, pow pow.PoW, txpool *TxPool, chainManager *ChainManager, eventMux *event.TypeMux) *BlockProcessor { sm := &BlockProcessor{ db: db, extraDb: extra, @@ -217,7 +217,7 @@ func (sm *BlockProcessor) processWithParent(block, parent *types.Block) (td *big // Commit state objects/accounts to a temporary trie (does not save) // used to calculate the state root. - state.Update(ethutil.Big0) + state.Update(common.Big0) if !bytes.Equal(header.Root, state.Root()) { err = fmt.Errorf("invalid merkle root. received=%x got=%x", header.Root, state.Root()) return @@ -352,7 +352,7 @@ func (sm *BlockProcessor) GetLogs(block *types.Block) (logs state.Logs, err erro return state.Logs(), nil } -func putTx(db ethutil.Database, tx *types.Transaction) { +func putTx(db common.Database, tx *types.Transaction) { rlpEnc, err := rlp.EncodeToBytes(tx) if err != nil { statelogger.Infoln("Failed encoding tx", err) diff --git a/core/chain_makers.go b/core/chain_makers.go index f140b5c7e..59c297dbe 100644 --- a/core/chain_makers.go +++ b/core/chain_makers.go @@ -5,7 +5,7 @@ import ( "math/big" "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/pow" "github.com/ethereum/go-ethereum/state" @@ -33,36 +33,36 @@ func NewBlockFromParent(addr []byte, parent *types.Block) *types.Block { return newBlockFromParent(addr, parent) } -func MakeBlock(bman *BlockProcessor, parent *types.Block, i int, db ethutil.Database, seed int) *types.Block { +func MakeBlock(bman *BlockProcessor, parent *types.Block, i int, db common.Database, seed int) *types.Block { return makeBlock(bman, parent, i, db, seed) } -func MakeChain(bman *BlockProcessor, parent *types.Block, max int, db ethutil.Database, seed int) types.Blocks { +func MakeChain(bman *BlockProcessor, parent *types.Block, max int, db common.Database, seed int) types.Blocks { return makeChain(bman, parent, max, db, seed) } -func NewChainMan(block *types.Block, eventMux *event.TypeMux, db ethutil.Database) *ChainManager { +func NewChainMan(block *types.Block, eventMux *event.TypeMux, db common.Database) *ChainManager { return newChainManager(block, eventMux, db) } -func NewBlockProc(db ethutil.Database, txpool *TxPool, cman *ChainManager, eventMux *event.TypeMux) *BlockProcessor { +func NewBlockProc(db common.Database, txpool *TxPool, cman *ChainManager, eventMux *event.TypeMux) *BlockProcessor { return newBlockProcessor(db, txpool, cman, eventMux) } -func NewCanonical(n int, db ethutil.Database) (*BlockProcessor, error) { +func NewCanonical(n int, db common.Database) (*BlockProcessor, error) { return newCanonical(n, db) } // block time is fixed at 10 seconds func newBlockFromParent(addr []byte, parent *types.Block) *types.Block { - block := types.NewBlock(parent.Hash(), addr, parent.Root(), ethutil.BigPow(2, 32), 0, "") + block := types.NewBlock(parent.Hash(), addr, parent.Root(), common.BigPow(2, 32), 0, "") block.SetUncles(nil) block.SetTransactions(nil) block.SetReceipts(nil) header := block.Header() header.Difficulty = CalcDifficulty(block.Header(), parent.Header()) - header.Number = new(big.Int).Add(parent.Header().Number, ethutil.Big1) + header.Number = new(big.Int).Add(parent.Header().Number, common.Big1) header.Time = parent.Header().Time + 10 header.GasLimit = CalcGasLimit(parent, block) @@ -73,22 +73,22 @@ func newBlockFromParent(addr []byte, parent *types.Block) *types.Block { // Actually make a block by simulating what miner would do // we seed chains by the first byte of the coinbase -func makeBlock(bman *BlockProcessor, parent *types.Block, i int, db ethutil.Database, seed int) *types.Block { - addr := ethutil.LeftPadBytes([]byte{byte(i)}, 20) +func makeBlock(bman *BlockProcessor, parent *types.Block, i int, db common.Database, seed int) *types.Block { + addr := common.LeftPadBytes([]byte{byte(i)}, 20) addr[0] = byte(seed) block := newBlockFromParent(addr, parent) state := state.New(block.Root(), db) cbase := state.GetOrNewStateObject(addr) cbase.SetGasPool(CalcGasLimit(parent, block)) cbase.AddBalance(BlockReward) - state.Update(ethutil.Big0) + state.Update(common.Big0) block.SetRoot(state.Root()) return block } // Make a chain with real blocks // Runs ProcessWithParent to get proper state roots -func makeChain(bman *BlockProcessor, parent *types.Block, max int, db ethutil.Database, seed int) types.Blocks { +func makeChain(bman *BlockProcessor, parent *types.Block, max int, db common.Database, seed int) types.Blocks { bman.bc.currentBlock = parent blocks := make(types.Blocks, max) for i := 0; i < max; i++ { @@ -107,7 +107,7 @@ func makeChain(bman *BlockProcessor, parent *types.Block, max int, db ethutil.Da // Create a new chain manager starting from given block // Effectively a fork factory -func newChainManager(block *types.Block, eventMux *event.TypeMux, db ethutil.Database) *ChainManager { +func newChainManager(block *types.Block, eventMux *event.TypeMux, db common.Database) *ChainManager { bc := &ChainManager{blockDb: db, stateDb: db, genesisBlock: GenesisBlock(db), eventMux: eventMux} if block == nil { bc.Reset() @@ -119,14 +119,14 @@ func newChainManager(block *types.Block, eventMux *event.TypeMux, db ethutil.Dat } // block processor with fake pow -func newBlockProcessor(db ethutil.Database, txpool *TxPool, cman *ChainManager, eventMux *event.TypeMux) *BlockProcessor { +func newBlockProcessor(db common.Database, txpool *TxPool, cman *ChainManager, eventMux *event.TypeMux) *BlockProcessor { bman := NewBlockProcessor(db, db, FakePow{}, txpool, newChainManager(nil, eventMux, db), eventMux) return bman } // Make a new, deterministic canonical chain by running InsertChain // on result of makeChain -func newCanonical(n int, db ethutil.Database) (*BlockProcessor, error) { +func newCanonical(n int, db common.Database) (*BlockProcessor, error) { eventMux := &event.TypeMux{} txpool := NewTxPool(eventMux) diff --git a/core/chain_manager.go b/core/chain_manager.go index 0b7dcf293..ff91b0427 100644 --- a/core/chain_manager.go +++ b/core/chain_manager.go @@ -7,7 +7,7 @@ import ( "sync" "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/rlp" @@ -60,7 +60,7 @@ func CalculateTD(block, parent *types.Block) *big.Int { func CalcGasLimit(parent, block *types.Block) *big.Int { if block.Number().Cmp(big.NewInt(0)) == 0 { - return ethutil.BigPow(10, 6) + return common.BigPow(10, 6) } // ((1024-1) * parent.gasLimit + (gasUsed * 6 / 5)) / 1024 @@ -71,13 +71,13 @@ func CalcGasLimit(parent, block *types.Block) *big.Int { result := new(big.Int).Add(previous, curInt) result.Div(result, big.NewInt(1024)) - return ethutil.BigMax(GenesisGasLimit, result) + return common.BigMax(GenesisGasLimit, result) } type ChainManager struct { //eth EthManager - blockDb ethutil.Database - stateDb ethutil.Database + blockDb common.Database + stateDb common.Database processor types.BlockProcessor eventMux *event.TypeMux genesisBlock *types.Block @@ -94,7 +94,7 @@ type ChainManager struct { quit chan struct{} } -func NewChainManager(blockDb, stateDb ethutil.Database, mux *event.TypeMux) *ChainManager { +func NewChainManager(blockDb, stateDb common.Database, mux *event.TypeMux) *ChainManager { bc := &ChainManager{blockDb: blockDb, stateDb: stateDb, genesisBlock: GenesisBlock(stateDb), eventMux: mux, quit: make(chan struct{})} bc.setLastBlock() bc.transState = bc.State().Copy() @@ -173,7 +173,7 @@ func (bc *ChainManager) setLastBlock() { bc.lastBlockHash = block.Hash() // Set the last know difficulty (might be 0x0 as initial value, Genesis) - bc.td = ethutil.BigD(bc.blockDb.LastKnownTD()) + bc.td = common.BigD(bc.blockDb.LastKnownTD()) } else { bc.Reset() } @@ -198,7 +198,7 @@ func (bc *ChainManager) NewBlock(coinbase []byte) *types.Block { parentHash, coinbase, root, - ethutil.BigPow(2, 32), + common.BigPow(2, 32), 0, "") block.SetUncles(nil) @@ -209,7 +209,7 @@ func (bc *ChainManager) NewBlock(coinbase []byte) *types.Block { if parent != nil { header := block.Header() header.Difficulty = CalcDifficulty(block.Header(), parent.Header()) - header.Number = new(big.Int).Add(parent.Header().Number, ethutil.Big1) + header.Number = new(big.Int).Add(parent.Header().Number, common.Big1) header.GasLimit = CalcGasLimit(parent, block) } @@ -230,7 +230,7 @@ func (bc *ChainManager) Reset() { bc.insert(bc.genesisBlock) bc.currentBlock = bc.genesisBlock - bc.setTotalDifficulty(ethutil.Big("0")) + bc.setTotalDifficulty(common.Big("0")) } func (bc *ChainManager) removeBlock(block *types.Block) { @@ -263,11 +263,11 @@ func (self *ChainManager) Export() []byte { blocks[block.NumberU64()] = block } - return ethutil.Encode(blocks) + return common.Encode(blocks) } func (bc *ChainManager) insert(block *types.Block) { - //encodedBlock := ethutil.Encode(block) + //encodedBlock := common.Encode(block) bc.blockDb.Put([]byte("LastBlock"), block.Hash()) bc.currentBlock = block bc.lastBlockHash = block.Hash() @@ -277,7 +277,7 @@ func (bc *ChainManager) insert(block *types.Block) { } func (bc *ChainManager) write(block *types.Block) { - encodedBlock := ethutil.Encode(block.RlpDataForStorage()) + encodedBlock := common.Encode(block.RlpDataForStorage()) key := append(blockHashPre, block.Hash()...) bc.blockDb.Put(key, encodedBlock) @@ -309,7 +309,7 @@ func (self *ChainManager) GetBlockHashesFromHash(hash []byte, max uint64) (chain } chain = append(chain, block.Hash()) - if block.Header().Number.Cmp(ethutil.Big0) <= 0 { + if block.Header().Number.Cmp(common.Big0) <= 0 { break } } @@ -434,7 +434,7 @@ func (self *ChainManager) InsertChain(chain types.Blocks) error { // Compare the TD of the last known block in the canonical chain to make sure it's greater. // At this point it's possible that a different chain (fork) becomes the new canonical chain. if td.Cmp(self.td) > 0 { - if block.Header().Number.Cmp(new(big.Int).Add(cblock.Header().Number, ethutil.Big1)) < 0 { + if block.Header().Number.Cmp(new(big.Int).Add(cblock.Header().Number, common.Big1)) < 0 { chainlogger.Infof("Split detected. New head #%v (%x) TD=%v, was #%v (%x) TD=%v\n", block.Header().Number, block.Hash()[:4], td, cblock.Header().Number, cblock.Hash()[:4], self.td) queue[i] = ChainSplitEvent{block} @@ -446,10 +446,10 @@ func (self *ChainManager) InsertChain(chain types.Blocks) error { /* XXX crashes jsonlogger.LogJson(&logger.EthChainNewHead{ - BlockHash: ethutil.Bytes2Hex(block.Hash()), + BlockHash: common.Bytes2Hex(block.Hash()), BlockNumber: block.Number(), - ChainHeadHash: ethutil.Bytes2Hex(cblock.Hash()), - BlockPrevHash: ethutil.Bytes2Hex(block.ParentHash()), + ChainHeadHash: common.Bytes2Hex(cblock.Hash()), + BlockPrevHash: common.Bytes2Hex(block.ParentHash()), }) */ diff --git a/core/genesis.go b/core/genesis.go index 9c82a28c8..bfd51f196 100644 --- a/core/genesis.go +++ b/core/genesis.go @@ -8,7 +8,7 @@ import ( "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/state" ) @@ -19,21 +19,21 @@ import ( var ZeroHash256 = make([]byte, 32) var ZeroHash160 = make([]byte, 20) var ZeroHash512 = make([]byte, 64) -var EmptyShaList = crypto.Sha3(ethutil.Encode([]interface{}{})) -var EmptyListRoot = crypto.Sha3(ethutil.Encode("")) +var EmptyShaList = crypto.Sha3(common.Encode([]interface{}{})) +var EmptyListRoot = crypto.Sha3(common.Encode("")) var GenesisDiff = big.NewInt(131072) var GenesisGasLimit = big.NewInt(3141592) -func GenesisBlock(db ethutil.Database) *types.Block { +func GenesisBlock(db common.Database) *types.Block { genesis := types.NewBlock(ZeroHash256, ZeroHash160, nil, GenesisDiff, 42, "") - genesis.Header().Number = ethutil.Big0 + genesis.Header().Number = common.Big0 genesis.Header().GasLimit = GenesisGasLimit - genesis.Header().GasUsed = ethutil.Big0 + genesis.Header().GasUsed = common.Big0 genesis.Header().Time = 0 genesis.Header().MixDigest = make([]byte, 32) - genesis.Td = ethutil.Big0 + genesis.Td = common.Big0 genesis.SetUncles([]*types.Header{}) genesis.SetTransactions(types.Transactions{}) @@ -48,9 +48,9 @@ func GenesisBlock(db ethutil.Database) *types.Block { statedb := state.New(genesis.Root(), db) for addr, account := range accounts { - codedAddr := ethutil.Hex2Bytes(addr) + codedAddr := common.Hex2Bytes(addr) accountState := statedb.GetAccount(codedAddr) - accountState.SetBalance(ethutil.Big(account.Balance)) + accountState.SetBalance(common.Big(account.Balance)) statedb.UpdateStateObject(accountState) } statedb.Sync() diff --git a/core/helper_test.go b/core/helper_test.go index b7f05db64..1e0ed178b 100644 --- a/core/helper_test.go +++ b/core/helper_test.go @@ -7,7 +7,7 @@ import ( "github.com/ethereum/go-ethereum/core/types" // "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/event" ) @@ -16,7 +16,7 @@ type TestManager struct { // stateManager *StateManager eventMux *event.TypeMux - db ethutil.Database + db common.Database txPool *TxPool blockChain *ChainManager Blocks []*types.Block @@ -58,7 +58,7 @@ func (tm *TestManager) EventMux() *event.TypeMux { // return nil // } -func (tm *TestManager) Db() ethutil.Database { +func (tm *TestManager) Db() common.Database { return tm.db } diff --git a/core/manager.go b/core/manager.go index c4052cc05..9b5407a9e 100644 --- a/core/manager.go +++ b/core/manager.go @@ -1,7 +1,7 @@ package core import ( - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/p2p" ) @@ -13,7 +13,7 @@ type Backend interface { PeerCount() int IsListening() bool Peers() []*p2p.Peer - BlockDb() ethutil.Database - StateDb() ethutil.Database + BlockDb() common.Database + StateDb() common.Database EventMux() *event.TypeMux } diff --git a/core/state_transition.go b/core/state_transition.go index f49aed874..279abee62 100644 --- a/core/state_transition.go +++ b/core/state_transition.go @@ -5,7 +5,7 @@ import ( "math/big" "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/state" "github.com/ethereum/go-ethereum/vm" ) @@ -58,7 +58,7 @@ type Message interface { func AddressFromMessage(msg Message) []byte { // Generate a new address - return crypto.Sha3(ethutil.NewValue([]interface{}{msg.From(), msg.Nonce()}).Encode())[12:] + return crypto.Sha3(common.NewValue([]interface{}{msg.From(), msg.Nonce()}).Encode())[12:] } func MessageCreatesContract(msg Message) bool { @@ -226,9 +226,9 @@ func (self *StateTransition) refundGas() { remaining := new(big.Int).Mul(self.gas, self.msg.GasPrice()) sender.AddBalance(remaining) - uhalf := new(big.Int).Div(self.gasUsed(), ethutil.Big2) + uhalf := new(big.Int).Div(self.gasUsed(), common.Big2) for addr, ref := range self.state.Refunds() { - refund := ethutil.BigMin(uhalf, ref) + refund := common.BigMin(uhalf, ref) self.gas.Add(self.gas, refund) self.state.AddBalance([]byte(addr), refund.Mul(refund, self.msg.GasPrice())) } diff --git a/core/transaction_pool.go b/core/transaction_pool.go index bd377f679..515cc2040 100644 --- a/core/transaction_pool.go +++ b/core/transaction_pool.go @@ -6,7 +6,7 @@ import ( "sync" "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/logger" ) @@ -113,13 +113,13 @@ func (self *TxPool) add(tx *types.Transaction) error { var to string if len(tx.To()) > 0 { - to = ethutil.Bytes2Hex(tx.To()[:4]) + to = common.Bytes2Hex(tx.To()[:4]) } else { to = "[NEW_CONTRACT]" } var from string if len(tx.From()) > 0 { - from = ethutil.Bytes2Hex(tx.From()[:4]) + from = common.Bytes2Hex(tx.From()[:4]) } else { return errors.New(fmt.Sprintf("FROM ADDRESS MUST BE POSITIVE (was %v)", tx.From())) } diff --git a/core/transaction_pool_test.go b/core/transaction_pool_test.go index b2d981f01..418cb0415 100644 --- a/core/transaction_pool_test.go +++ b/core/transaction_pool_test.go @@ -7,13 +7,13 @@ import ( "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/state" ) // State query interface -type stateQuery struct{ db ethutil.Database } +type stateQuery struct{ db common.Database } func SQ() stateQuery { db, _ := ethdb.NewMemDatabase() @@ -25,7 +25,7 @@ func (self stateQuery) GetAccount(addr []byte) *state.StateObject { } func transaction() *types.Transaction { - return types.NewTransactionMessage(make([]byte, 20), ethutil.Big0, ethutil.Big0, ethutil.Big0, nil) + return types.NewTransactionMessage(make([]byte, 20), common.Big0, common.Big0, common.Big0, nil) } func setup() (*TxPool, *ecdsa.PrivateKey) { diff --git a/core/types/block.go b/core/types/block.go index ba6ef6014..2d65cdca6 100644 --- a/core/types/block.go +++ b/core/types/block.go @@ -9,7 +9,7 @@ import ( "time" "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/rlp" ) @@ -74,11 +74,11 @@ func (self *Header) RlpData() interface{} { } func (self *Header) Hash() []byte { - return crypto.Sha3(ethutil.Encode(self.rlpData(true))) + return crypto.Sha3(common.Encode(self.rlpData(true))) } func (self *Header) HashNoNonce() []byte { - return crypto.Sha3(ethutil.Encode(self.rlpData(false))) + return crypto.Sha3(common.Encode(self.rlpData(false))) } type Block struct { @@ -148,7 +148,7 @@ func (self *Block) Uncles() []*Header { func (self *Block) SetUncles(uncleHeaders []*Header) { self.uncles = uncleHeaders - self.header.UncleHash = crypto.Sha3(ethutil.Encode(uncleHeaders)) + self.header.UncleHash = crypto.Sha3(common.Encode(uncleHeaders)) } func (self *Block) Transactions() Transactions { @@ -213,7 +213,7 @@ func (self *Block) GasLimit() *big.Int { return self.header.GasLimit } func (self *Block) GasUsed() *big.Int { return self.header.GasUsed } func (self *Block) Root() []byte { return self.header.Root } func (self *Block) SetRoot(root []byte) { self.header.Root = root } -func (self *Block) Size() ethutil.StorageSize { return ethutil.StorageSize(len(ethutil.Encode(self))) } +func (self *Block) Size() common.StorageSize { return common.StorageSize(len(common.Encode(self))) } func (self *Block) GetTransaction(i int) *Transaction { if len(self.transactions) > i { return self.transactions[i] diff --git a/core/types/bloom9.go b/core/types/bloom9.go index 578265a34..af76f226f 100644 --- a/core/types/bloom9.go +++ b/core/types/bloom9.go @@ -4,7 +4,7 @@ import ( "math/big" "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/state" ) @@ -14,7 +14,7 @@ func CreateBloom(receipts Receipts) []byte { bin.Or(bin, LogsBloom(receipt.logs)) } - return ethutil.LeftPadBytes(bin.Bytes(), 256) + return common.LeftPadBytes(bin.Bytes(), 256) } func LogsBloom(logs state.Logs) *big.Int { @@ -28,7 +28,7 @@ func LogsBloom(logs state.Logs) *big.Int { } for _, b := range data { - bin.Or(bin, ethutil.BigD(bloom9(crypto.Sha3(b)).Bytes())) + bin.Or(bin, common.BigD(bloom9(crypto.Sha3(b)).Bytes())) } } @@ -48,7 +48,7 @@ func bloom9(b []byte) *big.Int { } func BloomLookup(bin, topic []byte) bool { - bloom := ethutil.BigD(bin) + bloom := common.BigD(bin) cmp := bloom9(crypto.Sha3(topic)) return bloom.And(bloom, cmp).Cmp(cmp) == 0 diff --git a/core/types/bloom9_test.go b/core/types/bloom9_test.go index 74e00cac6..0841bb859 100644 --- a/core/types/bloom9_test.go +++ b/core/types/bloom9_test.go @@ -22,10 +22,10 @@ func TestBloom9(t *testing.T) { func TestAddress(t *testing.T) { block := &Block{} - block.Coinbase = ethutil.Hex2Bytes("22341ae42d6dd7384bc8584e50419ea3ac75b83f") + block.Coinbase = common.Hex2Bytes("22341ae42d6dd7384bc8584e50419ea3ac75b83f") fmt.Printf("%x\n", crypto.Sha3(block.Coinbase)) bin := CreateBloom(block) - fmt.Printf("bin = %x\n", ethutil.LeftPadBytes(bin, 64)) + fmt.Printf("bin = %x\n", common.LeftPadBytes(bin, 64)) } */ diff --git a/core/types/derive_sha.go b/core/types/derive_sha.go index b2c442210..593a31f1c 100644 --- a/core/types/derive_sha.go +++ b/core/types/derive_sha.go @@ -2,7 +2,7 @@ package types import ( "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/trie" ) @@ -15,7 +15,7 @@ func DeriveSha(list DerivableList) []byte { db, _ := ethdb.NewMemDatabase() trie := trie.New(nil, db) for i := 0; i < list.Len(); i++ { - trie.Update(ethutil.Encode(i), list.GetRlp(i)) + trie.Update(common.Encode(i), list.GetRlp(i)) } return trie.Root() diff --git a/core/types/receipt.go b/core/types/receipt.go index 49e68e233..be14d0e0e 100644 --- a/core/types/receipt.go +++ b/core/types/receipt.go @@ -5,7 +5,7 @@ import ( "fmt" "math/big" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/state" ) @@ -17,10 +17,10 @@ type Receipt struct { } func NewReceipt(root []byte, cumalativeGasUsed *big.Int) *Receipt { - return &Receipt{PostState: ethutil.CopyBytes(root), CumulativeGasUsed: new(big.Int).Set(cumalativeGasUsed)} + return &Receipt{PostState: common.CopyBytes(root), CumulativeGasUsed: new(big.Int).Set(cumalativeGasUsed)} } -func NewRecieptFromValue(val *ethutil.Value) *Receipt { +func NewRecieptFromValue(val *common.Value) *Receipt { r := &Receipt{} r.RlpValueDecode(val) @@ -31,7 +31,7 @@ func (self *Receipt) SetLogs(logs state.Logs) { self.logs = logs } -func (self *Receipt) RlpValueDecode(decoder *ethutil.Value) { +func (self *Receipt) RlpValueDecode(decoder *common.Value) { self.PostState = decoder.Get(0).Bytes() self.CumulativeGasUsed = decoder.Get(1).BigInt() self.Bloom = decoder.Get(2).Bytes() @@ -47,7 +47,7 @@ func (self *Receipt) RlpData() interface{} { } func (self *Receipt) RlpEncode() []byte { - return ethutil.Encode(self.RlpData()) + return common.Encode(self.RlpData()) } func (self *Receipt) Cmp(other *Receipt) bool { @@ -74,8 +74,8 @@ func (self Receipts) RlpData() interface{} { } func (self Receipts) RlpEncode() []byte { - return ethutil.Encode(self.RlpData()) + return common.Encode(self.RlpData()) } func (self Receipts) Len() int { return len(self) } -func (self Receipts) GetRlp(i int) []byte { return ethutil.Rlp(self[i]) } +func (self Receipts) GetRlp(i int) []byte { return common.Rlp(self[i]) } diff --git a/core/types/transaction.go b/core/types/transaction.go index 88a718f93..dcd48af11 100644 --- a/core/types/transaction.go +++ b/core/types/transaction.go @@ -8,7 +8,7 @@ import ( "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto/secp256k1" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/rlp" ) @@ -42,7 +42,7 @@ func NewTransactionFromBytes(data []byte) *Transaction { return tx } -func NewTransactionFromAmount(val *ethutil.Value) *Transaction { +func NewTransactionFromAmount(val *common.Value) *Transaction { tx := &Transaction{} tx.RlpValueDecode(val) @@ -52,7 +52,7 @@ func NewTransactionFromAmount(val *ethutil.Value) *Transaction { func (tx *Transaction) Hash() []byte { data := []interface{}{tx.AccountNonce, tx.Price, tx.GasLimit, tx.Recipient, tx.Amount, tx.Payload} - return crypto.Sha3(ethutil.Encode(data)) + return crypto.Sha3(common.Encode(data)) } func (self *Transaction) Data() []byte { @@ -89,8 +89,8 @@ func (self *Transaction) To() []byte { func (tx *Transaction) Curve() (v byte, r []byte, s []byte) { v = byte(tx.V) - r = ethutil.LeftPadBytes(tx.R, 32) - s = ethutil.LeftPadBytes(tx.S, 32) + r = common.LeftPadBytes(tx.R, 32) + s = common.LeftPadBytes(tx.S, 32) return } @@ -159,14 +159,14 @@ func (tx *Transaction) RlpData() interface{} { } func (tx *Transaction) RlpEncode() []byte { - return ethutil.Encode(tx) + return common.Encode(tx) } func (tx *Transaction) RlpDecode(data []byte) { rlp.Decode(bytes.NewReader(data), tx) } -func (tx *Transaction) RlpValueDecode(decoder *ethutil.Value) { +func (tx *Transaction) RlpValueDecode(decoder *common.Value) { tx.AccountNonce = decoder.Get(0).Uint() tx.Price = decoder.Get(1).BigInt() tx.GasLimit = decoder.Get(2).BigInt() @@ -206,7 +206,7 @@ func (tx *Transaction) String() string { tx.V, tx.R, tx.S, - ethutil.Encode(tx), + common.Encode(tx), ) } @@ -225,7 +225,7 @@ func (self Transactions) RlpData() interface{} { } func (s Transactions) Len() int { return len(s) } func (s Transactions) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s Transactions) GetRlp(i int) []byte { return ethutil.Rlp(s[i]) } +func (s Transactions) GetRlp(i int) []byte { return common.Rlp(s[i]) } type TxByNonce struct{ Transactions } diff --git a/crypto/crypto.go b/crypto/crypto.go index 90e2c8939..bc72928ac 100644 --- a/crypto/crypto.go +++ b/crypto/crypto.go @@ -19,7 +19,7 @@ import ( "github.com/ethereum/go-ethereum/crypto/ecies" "github.com/ethereum/go-ethereum/crypto/secp256k1" "github.com/ethereum/go-ethereum/crypto/sha3" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "golang.org/x/crypto/pbkdf2" "golang.org/x/crypto/ripemd160" ) @@ -39,7 +39,7 @@ func Sha3(data ...[]byte) []byte { // Creates an ethereum address given the bytes and the nonce func CreateAddress(b []byte, nonce uint64) []byte { - return Sha3(ethutil.NewValue([]interface{}{b, nonce}).Encode())[12:] + return Sha3(common.NewValue([]interface{}{b, nonce}).Encode())[12:] } func Sha256(data []byte) []byte { @@ -74,7 +74,7 @@ func ToECDSA(prv []byte) *ecdsa.PrivateKey { priv := new(ecdsa.PrivateKey) priv.PublicKey.Curve = S256() - priv.D = ethutil.BigD(prv) + priv.D = common.BigD(prv) priv.PublicKey.X, priv.PublicKey.Y = S256().ScalarBaseMult(prv) return priv } @@ -143,7 +143,7 @@ func Sign(hash []byte, prv *ecdsa.PrivateKey) (sig []byte, err error) { return nil, fmt.Errorf("hash is required to be exactly 32 bytes (%d)", len(hash)) } - sig, err = secp256k1.Sign(hash, ethutil.LeftPadBytes(prv.D.Bytes(), prv.Params().BitSize/8)) + sig, err = secp256k1.Sign(hash, common.LeftPadBytes(prv.D.Bytes(), prv.Params().BitSize/8)) return } @@ -198,7 +198,7 @@ func decryptPreSaleKey(fileContent []byte, password string) (key *Key, err error Address: PubkeyToAddress(ecKey.PublicKey), PrivateKey: ecKey, } - derivedAddr := ethutil.Bytes2Hex(key.Address) + derivedAddr := common.Bytes2Hex(key.Address) expectedAddr := preSaleKeyStruct.EthAddr if derivedAddr != expectedAddr { err = errors.New("decrypted addr not equal to expected addr") diff --git a/crypto/crypto_test.go b/crypto/crypto_test.go index c68856622..754287641 100644 --- a/crypto/crypto_test.go +++ b/crypto/crypto_test.go @@ -8,7 +8,7 @@ import ( "time" "github.com/ethereum/go-ethereum/crypto/secp256k1" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" ) // These tests are sanity checks. @@ -53,7 +53,7 @@ func BenchmarkSha3(b *testing.B) { func Test0Key(t *testing.T) { t.Skip() - key := ethutil.Hex2Bytes("1111111111111111111111111111111111111111111111111111111111111111") + key := common.Hex2Bytes("1111111111111111111111111111111111111111111111111111111111111111") p, err := secp256k1.GeneratePubKey(key) addr := Sha3(p[1:])[12:] diff --git a/crypto/encrypt_decrypt_test.go b/crypto/encrypt_decrypt_test.go index 85b43c406..6e5b40a37 100644 --- a/crypto/encrypt_decrypt_test.go +++ b/crypto/encrypt_decrypt_test.go @@ -5,13 +5,13 @@ import ( "fmt" "testing" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" ) func TestBox(t *testing.T) { - prv1 := ToECDSA(ethutil.Hex2Bytes("4b50fa71f5c3eeb8fdc452224b2395af2fcc3d125e06c32c82e048c0559db03f")) - prv2 := ToECDSA(ethutil.Hex2Bytes("d0b043b4c5d657670778242d82d68a29d25d7d711127d17b8e299f156dad361a")) - pub2 := ToECDSAPub(ethutil.Hex2Bytes("04bd27a63c91fe3233c5777e6d3d7b39204d398c8f92655947eb5a373d46e1688f022a1632d264725cbc7dc43ee1cfebde42fa0a86d08b55d2acfbb5e9b3b48dc5")) + prv1 := ToECDSA(common.Hex2Bytes("4b50fa71f5c3eeb8fdc452224b2395af2fcc3d125e06c32c82e048c0559db03f")) + prv2 := ToECDSA(common.Hex2Bytes("d0b043b4c5d657670778242d82d68a29d25d7d711127d17b8e299f156dad361a")) + pub2 := ToECDSAPub(common.Hex2Bytes("04bd27a63c91fe3233c5777e6d3d7b39204d398c8f92655947eb5a373d46e1688f022a1632d264725cbc7dc43ee1cfebde42fa0a86d08b55d2acfbb5e9b3b48dc5")) message := []byte("Hello, world.") ct, err := Encrypt(pub2, message) diff --git a/crypto/key_store_test.go b/crypto/key_store_test.go index 11531d460..f0a1e567b 100644 --- a/crypto/key_store_test.go +++ b/crypto/key_store_test.go @@ -2,13 +2,13 @@ package crypto import ( "github.com/ethereum/go-ethereum/crypto/randentropy" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "reflect" "testing" ) func TestKeyStorePlain(t *testing.T) { - ks := NewKeyStorePlain(ethutil.DefaultDataDir()) + ks := NewKeyStorePlain(common.DefaultDataDir()) pass := "" // not used but required by API k1, err := ks.GenerateNewKey(randentropy.Reader, pass) if err != nil { @@ -36,7 +36,7 @@ func TestKeyStorePlain(t *testing.T) { } func TestKeyStorePassphrase(t *testing.T) { - ks := NewKeyStorePassphrase(ethutil.DefaultDataDir()) + ks := NewKeyStorePassphrase(common.DefaultDataDir()) pass := "foo" k1, err := ks.GenerateNewKey(randentropy.Reader, pass) if err != nil { @@ -62,7 +62,7 @@ func TestKeyStorePassphrase(t *testing.T) { } func TestKeyStorePassphraseDecryptionFail(t *testing.T) { - ks := NewKeyStorePassphrase(ethutil.DefaultDataDir()) + ks := NewKeyStorePassphrase(common.DefaultDataDir()) pass := "foo" k1, err := ks.GenerateNewKey(randentropy.Reader, pass) if err != nil { @@ -90,7 +90,7 @@ func TestImportPreSaleKey(t *testing.T) { // python pyethsaletool.py genwallet // with password "foo" fileContent := "{\"encseed\": \"26d87f5f2bf9835f9a47eefae571bc09f9107bb13d54ff12a4ec095d01f83897494cf34f7bed2ed34126ecba9db7b62de56c9d7cd136520a0427bfb11b8954ba7ac39b90d4650d3448e31185affcd74226a68f1e94b1108e6e0a4a91cdd83eba\", \"ethaddr\": \"d4584b5f6229b7be90727b0fc8c6b91bb427821f\", \"email\": \"gustav.simonsson@gmail.com\", \"btcaddr\": \"1EVknXyFC68kKNLkh6YnKzW41svSRoaAcx\"}" - ks := NewKeyStorePassphrase(ethutil.DefaultDataDir()) + ks := NewKeyStorePassphrase(common.DefaultDataDir()) pass := "foo" _, err := ImportPreSaleKey(ks, []byte(fileContent), pass) if err != nil { diff --git a/crypto/keypair.go b/crypto/keypair.go index da5788437..6702e6595 100644 --- a/crypto/keypair.go +++ b/crypto/keypair.go @@ -4,7 +4,7 @@ import ( "strings" "github.com/ethereum/go-ethereum/crypto/secp256k1" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" ) type KeyPair struct { @@ -40,19 +40,19 @@ func (k *KeyPair) Address() []byte { func (k *KeyPair) Mnemonic() string { if k.mnemonic == "" { - k.mnemonic = strings.Join(MnemonicEncode(ethutil.Bytes2Hex(k.PrivateKey)), " ") + k.mnemonic = strings.Join(MnemonicEncode(common.Bytes2Hex(k.PrivateKey)), " ") } return k.mnemonic } func (k *KeyPair) AsStrings() (string, string, string, string) { - return k.Mnemonic(), ethutil.Bytes2Hex(k.Address()), ethutil.Bytes2Hex(k.PrivateKey), ethutil.Bytes2Hex(k.PublicKey) + return k.Mnemonic(), common.Bytes2Hex(k.Address()), common.Bytes2Hex(k.PrivateKey), common.Bytes2Hex(k.PublicKey) } func (k *KeyPair) RlpEncode() []byte { return k.RlpValue().Encode() } -func (k *KeyPair) RlpValue() *ethutil.Value { - return ethutil.NewValue(k.PrivateKey) +func (k *KeyPair) RlpValue() *common.Value { + return common.NewValue(k.PrivateKey) } diff --git a/eth/backend.go b/eth/backend.go index 346fc43bc..42f2b5808 100644 --- a/eth/backend.go +++ b/eth/backend.go @@ -14,7 +14,7 @@ import ( "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/miner" @@ -65,7 +65,7 @@ type Config struct { // NewDB is used to create databases. // If nil, the default is to create leveldb databases on disk. - NewDB func(path string) (ethutil.Database, error) + NewDB func(path string) (common.Database, error) } func (cfg *Config) parseBootNodes() []*discover.Node { @@ -113,9 +113,9 @@ type Ethereum struct { shutdownChan chan bool // DB interfaces - blockDb ethutil.Database // Block chain database - stateDb ethutil.Database // State changes database - extraDb ethutil.Database // Extra database (txs, etc) + blockDb common.Database // Block chain database + stateDb common.Database // State changes database + extraDb common.Database // Extra database (txs, etc) //*** SERVICES *** // State manager for processing new blocks and managing the over all states @@ -146,7 +146,7 @@ func New(config *Config) (*Ethereum, error) { newdb := config.NewDB if newdb == nil { - newdb = func(path string) (ethutil.Database, error) { return ethdb.NewLDBDatabase(path) } + newdb = func(path string) (common.Database, error) { return ethdb.NewLDBDatabase(path) } } blockDb, err := newdb(path.Join(config.DataDir, "blockchain")) if err != nil { @@ -160,7 +160,7 @@ func New(config *Config) (*Ethereum, error) { // Perform database sanity checks d, _ := blockDb.Get([]byte("ProtocolVersion")) - protov := ethutil.NewValue(d).Uint() + protov := common.NewValue(d).Uint() if protov != ProtocolVersion && protov != 0 { path := path.Join(config.DataDir, "blockchain") return nil, fmt.Errorf("Database version mismatch. Protocol(%d / %d). `rm -rf %s`", protov, ProtocolVersion, path) @@ -246,9 +246,9 @@ func (s *Ethereum) TxPool() *core.TxPool { return s.txPool } func (s *Ethereum) BlockPool() *blockpool.BlockPool { return s.blockPool } func (s *Ethereum) Whisper() *whisper.Whisper { return s.whisper } func (s *Ethereum) EventMux() *event.TypeMux { return s.eventMux } -func (s *Ethereum) BlockDb() ethutil.Database { return s.blockDb } -func (s *Ethereum) StateDb() ethutil.Database { return s.stateDb } -func (s *Ethereum) ExtraDb() ethutil.Database { return s.extraDb } +func (s *Ethereum) BlockDb() common.Database { return s.blockDb } +func (s *Ethereum) StateDb() common.Database { return s.stateDb } +func (s *Ethereum) ExtraDb() common.Database { return s.extraDb } func (s *Ethereum) IsListening() bool { return true } // Always listening func (s *Ethereum) PeerCount() int { return s.net.PeerCount() } func (s *Ethereum) Peers() []*p2p.Peer { return s.net.Peers() } @@ -351,11 +351,11 @@ func (self *Ethereum) blockBroadcastLoop() { } } -func saveProtocolVersion(db ethutil.Database) { +func saveProtocolVersion(db common.Database) { d, _ := db.Get([]byte("ProtocolVersion")) - protocolVersion := ethutil.NewValue(d).Uint() + protocolVersion := common.NewValue(d).Uint() if protocolVersion == 0 { - db.Put([]byte("ProtocolVersion"), ethutil.NewValue(ProtocolVersion).Bytes()) + db.Put([]byte("ProtocolVersion"), common.NewValue(ProtocolVersion).Bytes()) } } diff --git a/eth/peer_util.go b/eth/peer_util.go index 6cf80cde2..18fef0ab5 100644 --- a/eth/peer_util.go +++ b/eth/peer_util.go @@ -3,19 +3,19 @@ package eth import ( "encoding/json" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" ) func WritePeers(path string, addresses []string) { if len(addresses) > 0 { data, _ := json.MarshalIndent(addresses, "", " ") - ethutil.WriteFile(path, data) + common.WriteFile(path, data) } } func ReadPeers(path string) (ips []string, err error) { var data string - data, err = ethutil.ReadAllFile(path) + data, err = common.ReadAllFile(path) if err != nil { json.Unmarshal([]byte(data), &ips) } diff --git a/eth/protocol.go b/eth/protocol.go index 708e22087..e368bbec5 100644 --- a/eth/protocol.go +++ b/eth/protocol.go @@ -7,7 +7,7 @@ import ( "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/errs" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/p2p" "github.com/ethereum/go-ethereum/rlp" @@ -167,7 +167,7 @@ func (self *ethProtocol) handle() error { } for _, tx := range txs { jsonlogger.LogJson(&logger.EthTxReceived{ - TxHash: ethutil.Bytes2Hex(tx.Hash()), + TxHash: common.Bytes2Hex(tx.Hash()), RemoteId: self.peer.ID().String(), }) } @@ -183,7 +183,7 @@ func (self *ethProtocol) handle() error { request.Amount = maxHashes } hashes := self.chainManager.GetBlockHashesFromHash(request.Hash, request.Amount) - return p2p.EncodeMsg(self.rw, BlockHashesMsg, ethutil.ByteSliceToInterface(hashes)...) + return p2p.EncodeMsg(self.rw, BlockHashesMsg, common.ByteSliceToInterface(hashes)...) case BlockHashesMsg: msgStream := rlp.NewStream(msg.Payload) @@ -259,10 +259,10 @@ func (self *ethProtocol) handle() error { _, chainHead, _ := self.chainManager.Status() jsonlogger.LogJson(&logger.EthChainReceivedNewBlock{ - BlockHash: ethutil.Bytes2Hex(hash), + BlockHash: common.Bytes2Hex(hash), BlockNumber: request.Block.Number(), // this surely must be zero - ChainHeadHash: ethutil.Bytes2Hex(chainHead), - BlockPrevHash: ethutil.Bytes2Hex(request.Block.ParentHash()), + ChainHeadHash: common.Bytes2Hex(chainHead), + BlockPrevHash: common.Bytes2Hex(request.Block.ParentHash()), RemoteId: self.peer.ID().String(), }) // to simplify backend interface adding a new block @@ -351,7 +351,7 @@ func (self *ethProtocol) requestBlockHashes(from []byte) error { func (self *ethProtocol) requestBlocks(hashes [][]byte) error { self.peer.Debugf("fetching %v blocks", len(hashes)) - return p2p.EncodeMsg(self.rw, GetBlocksMsg, ethutil.ByteSliceToInterface(hashes)...) + return p2p.EncodeMsg(self.rw, GetBlocksMsg, common.ByteSliceToInterface(hashes)...) } func (self *ethProtocol) protoError(code int, format string, params ...interface{}) (err *errs.Error) { diff --git a/eth/protocol_test.go b/eth/protocol_test.go index f499d033e..a2b59f117 100644 --- a/eth/protocol_test.go +++ b/eth/protocol_test.go @@ -12,7 +12,7 @@ import ( "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/errs" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" ethlogger "github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/p2p" "github.com/ethereum/go-ethereum/p2p/discover" @@ -223,7 +223,7 @@ func (self *ethProtocolTester) run() { func TestStatusMsgErrors(t *testing.T) { logInit() eth := newEth(t) - td := ethutil.Big1 + td := common.Big1 currentBlock := []byte{1} genesis := []byte{2} eth.chainManager.status = func() (*big.Int, []byte, []byte) { return td, currentBlock, genesis } diff --git a/ethdb/database.go b/ethdb/database.go index 4e3d01da0..cc2df5fa0 100644 --- a/ethdb/database.go +++ b/ethdb/database.go @@ -4,7 +4,7 @@ import ( "fmt" "github.com/ethereum/go-ethereum/compression/rle" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/syndtr/goleveldb/leveldb" "github.com/syndtr/goleveldb/leveldb/iterator" ) @@ -82,7 +82,7 @@ func (self *LDBDatabase) Print() { value := iter.Value() fmt.Printf("%x(%d): ", key, len(key)) - node := ethutil.NewValueFromBytes(value) + node := common.NewValueFromBytes(value) fmt.Printf("%v\n", node) } } diff --git a/ethdb/memory_database.go b/ethdb/memory_database.go index 48aa830e7..d914f47f8 100644 --- a/ethdb/memory_database.go +++ b/ethdb/memory_database.go @@ -3,7 +3,7 @@ package ethdb import ( "fmt" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" ) /* @@ -32,10 +32,10 @@ func (db *MemDatabase) Get(key []byte) ([]byte, error) { } /* -func (db *MemDatabase) GetKeys() []*ethutil.Key { +func (db *MemDatabase) GetKeys() []*common.Key { data, _ := db.Get([]byte("KeyRing")) - return []*ethutil.Key{ethutil.NewKeyFromBytes(data)} + return []*common.Key{common.NewKeyFromBytes(data)} } */ @@ -48,7 +48,7 @@ func (db *MemDatabase) Delete(key []byte) error { func (db *MemDatabase) Print() { for key, val := range db.db { fmt.Printf("%x(%d): ", key, len(key)) - node := ethutil.NewValueFromBytes(val) + node := common.NewValueFromBytes(val) fmt.Printf("%q\n", node.Interface()) } } diff --git a/ethutil/.gitignore b/ethutil/.gitignore deleted file mode 100644 index f725d58d1..000000000 --- a/ethutil/.gitignore +++ /dev/null @@ -1,12 +0,0 @@ -# See http://help.github.com/ignore-files/ for more about ignoring files. -# -# If you find yourself ignoring temporary files generated by your text editor -# or operating system, you probably want to add a global ignore instead: -# git config --global core.excludesfile ~/.gitignore_global - -/tmp -*/**/*un~ -*un~ -.DS_Store -*/**/.DS_Store - diff --git a/ethutil/.travis.yml b/ethutil/.travis.yml deleted file mode 100644 index 69359072d..000000000 --- a/ethutil/.travis.yml +++ /dev/null @@ -1,3 +0,0 @@ -language: go -go: - - 1.2 diff --git a/ethutil/README.md b/ethutil/README.md deleted file mode 100644 index 1ed56b71b..000000000 --- a/ethutil/README.md +++ /dev/null @@ -1,139 +0,0 @@ -# ethutil - -[![Build -Status](https://travis-ci.org/ethereum/go-ethereum.png?branch=master)](https://travis-ci.org/ethereum/go-ethereum) - -The ethutil package contains the ethereum utility library. - -# Installation - -`go get github.com/ethereum/ethutil-go` - -# Usage - -## RLP (Recursive Linear Prefix) Encoding - -RLP Encoding is an encoding scheme utilized by the Ethereum project. It -encodes any native value or list to string. - -More in depth information about the Encoding scheme see the [Wiki](http://wiki.ethereum.org/index.php/RLP) -article. - -```go -rlp := ethutil.Encode("doge") -fmt.Printf("%q\n", rlp) // => "\0x83dog" - -rlp = ethutil.Encode([]interface{}{"dog", "cat"}) -fmt.Printf("%q\n", rlp) // => "\0xc8\0x83dog\0x83cat" -decoded := ethutil.Decode(rlp) -fmt.Println(decoded) // => ["dog" "cat"] -``` - -## Patricia Trie - -Patricie Tree is a merkle trie utilized by the Ethereum project. - -More in depth information about the (modified) Patricia Trie can be -found on the [Wiki](http://wiki.ethereum.org/index.php/Patricia_Tree). - -The patricia trie uses a db as backend and could be anything as long as -it satisfies the Database interface found in `ethutil/db.go`. - -```go -db := NewDatabase() - -// db, root -trie := ethutil.NewTrie(db, "") - -trie.Put("puppy", "dog") -trie.Put("horse", "stallion") -trie.Put("do", "verb") -trie.Put("doge", "coin") - -// Look up the key "do" in the trie -out := trie.Get("do") -fmt.Println(out) // => verb - -trie.Delete("puppy") -``` - -The patricia trie, in combination with RLP, provides a robust, -cryptographically authenticated data structure that can be used to store -all (key, value) bindings. - -```go -// ... Create db/trie - -// Note that RLP uses interface slices as list -value := ethutil.Encode([]interface{}{"one", 2, "three", []interface{}{42}}) -// Store the RLP encoded value of the list -trie.Put("mykey", value) -``` - -## Value - -Value is a Generic Value which is used in combination with RLP data or -`([])interface{}` structures. It may serve as a bridge between RLP data -and actual real values and takes care of all the type checking and -casting. Unlike Go's `reflect.Value` it does not panic if it's unable to -cast to the requested value. It simple returns the base value of that -type (e.g. `Slice()` returns []interface{}, `Uint()` return 0, etc). - -### Creating a new Value - -`NewEmptyValue()` returns a new \*Value with it's initial value set to a -`[]interface{}` - -`AppendList()` appends a list to the current value. - -`Append(v)` appends the value (v) to the current value/list. - -```go -val := ethutil.NewEmptyValue().Append(1).Append("2") -val.AppendList().Append(3) -``` - -### Retrieving values - -`Get(i)` returns the `i` item in the list. - -`Uint()` returns the value as an unsigned int64. - -`Slice()` returns the value as a interface slice. - -`Str()` returns the value as a string. - -`Bytes()` returns the value as a byte slice. - -`Len()` assumes current to be a slice and returns its length. - -`Byte()` returns the value as a single byte. - -```go -val := ethutil.NewValue([]interface{}{1,"2",[]interface{}{3}}) -val.Get(0).Uint() // => 1 -val.Get(1).Str() // => "2" -s := val.Get(2) // => Value([]interface{}{3}) -s.Get(0).Uint() // => 3 -``` - -## Decoding - -Decoding streams of RLP data is simplified - -```go -val := ethutil.NewValueFromBytes(rlpData) -val.Get(0).Uint() -``` - -## Encoding - -Encoding from Value to RLP is done with the `Encode` method. The -underlying value can be anything RLP can encode (int, str, lists, bytes) - -```go -val := ethutil.NewValue([]interface{}{1,"2",[]interface{}{3}}) -rlp := val.Encode() -// Store the rlp data -Store(rlp) -``` diff --git a/ethutil/big.go b/ethutil/big.go deleted file mode 100644 index b77e0af8c..000000000 --- a/ethutil/big.go +++ /dev/null @@ -1,123 +0,0 @@ -package ethutil - -import "math/big" - -// Big pow -// -// Returns the power of two big integers -func BigPow(a, b int) *big.Int { - c := new(big.Int) - c.Exp(big.NewInt(int64(a)), big.NewInt(int64(b)), big.NewInt(0)) - - return c -} - -// Big -// -// Shortcut for new(big.Int).SetString(..., 0) -func Big(num string) *big.Int { - n := new(big.Int) - n.SetString(num, 0) - - return n -} - -// BigD -// -// Shortcut for new(big.Int).SetBytes(...) -func Bytes2Big(data []byte) *big.Int { - n := new(big.Int) - n.SetBytes(data) - - return n -} -func BigD(data []byte) *big.Int { return Bytes2Big(data) } - -func String2Big(num string) *big.Int { - n := new(big.Int) - n.SetString(num, 0) - return n -} - -func BitTest(num *big.Int, i int) bool { - return num.Bit(i) > 0 -} - -// To256 -// -// "cast" the big int to a 256 big int (i.e., limit to) -var tt256 = new(big.Int).Lsh(big.NewInt(1), 256) -var tt256m1 = new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), 256), big.NewInt(1)) -var tt255 = new(big.Int).Lsh(big.NewInt(1), 255) - -func U256(x *big.Int) *big.Int { - //if x.Cmp(Big0) < 0 { - // return new(big.Int).Add(tt256, x) - // } - - x.And(x, tt256m1) - - return x -} - -func S256(x *big.Int) *big.Int { - if x.Cmp(tt255) < 0 { - return x - } else { - // We don't want to modify x, ever - return new(big.Int).Sub(x, tt256) - } -} - -func FirstBitSet(v *big.Int) int { - for i := 0; i < v.BitLen(); i++ { - if v.Bit(i) > 0 { - return i - } - } - - return v.BitLen() -} - -// Big to bytes -// -// Returns the bytes of a big integer with the size specified by **base** -// Attempts to pad the byte array with zeros. -func BigToBytes(num *big.Int, base int) []byte { - ret := make([]byte, base/8) - - if len(num.Bytes()) > base/8 { - return num.Bytes() - } - - return append(ret[:len(ret)-len(num.Bytes())], num.Bytes()...) -} - -// Big copy -// -// Creates a copy of the given big integer -func BigCopy(src *big.Int) *big.Int { - return new(big.Int).Set(src) -} - -// Big max -// -// Returns the maximum size big integer -func BigMax(x, y *big.Int) *big.Int { - if x.Cmp(y) <= 0 { - return y - } - - return x -} - -// Big min -// -// Returns the minimum size big integer -func BigMin(x, y *big.Int) *big.Int { - if x.Cmp(y) >= 0 { - return y - } - - return x -} diff --git a/ethutil/big_test.go b/ethutil/big_test.go deleted file mode 100644 index bf3c96c6d..000000000 --- a/ethutil/big_test.go +++ /dev/null @@ -1,73 +0,0 @@ -package ethutil - -import ( - "bytes" - "testing" -) - -func TestMisc(t *testing.T) { - a := Big("10") - b := Big("57896044618658097711785492504343953926634992332820282019728792003956564819968") - c := []byte{1, 2, 3, 4} - z := BitTest(a, 1) - - if z != true { - t.Error("Expected true got", z) - } - - U256(a) - S256(a) - - U256(b) - S256(b) - - BigD(c) -} - -func TestBigMax(t *testing.T) { - a := Big("10") - b := Big("5") - - max1 := BigMax(a, b) - if max1 != a { - t.Errorf("Expected %d got %d", a, max1) - } - - max2 := BigMax(b, a) - if max2 != a { - t.Errorf("Expected %d got %d", a, max2) - } -} - -func TestBigMin(t *testing.T) { - a := Big("10") - b := Big("5") - - min1 := BigMin(a, b) - if min1 != b { - t.Errorf("Expected %d got %d", b, min1) - } - - min2 := BigMin(b, a) - if min2 != b { - t.Errorf("Expected %d got %d", b, min2) - } -} - -func TestBigCopy(t *testing.T) { - a := Big("10") - b := BigCopy(a) - c := Big("1000000000000") - y := BigToBytes(b, 16) - ybytes := []byte{0, 10} - z := BigToBytes(c, 16) - zbytes := []byte{232, 212, 165, 16, 0} - - if bytes.Compare(y, ybytes) != 0 { - t.Error("Got", ybytes) - } - - if bytes.Compare(z, zbytes) != 0 { - t.Error("Got", zbytes) - } -} diff --git a/ethutil/bytes.go b/ethutil/bytes.go deleted file mode 100644 index bd294f28a..000000000 --- a/ethutil/bytes.go +++ /dev/null @@ -1,234 +0,0 @@ -package ethutil - -import ( - "bytes" - "encoding/binary" - "encoding/hex" - "fmt" - "math/big" - "strings" -) - -type Bytes []byte - -func (self Bytes) String() string { - return string(self) -} - -func DeleteFromByteSlice(s [][]byte, hash []byte) [][]byte { - for i, h := range s { - if bytes.Compare(h, hash) == 0 { - return append(s[:i:i], s[i+1:]...) - } - } - - return s -} - -// Number to bytes -// -// Returns the number in bytes with the specified base -func NumberToBytes(num interface{}, bits int) []byte { - buf := new(bytes.Buffer) - err := binary.Write(buf, binary.BigEndian, num) - if err != nil { - fmt.Println("NumberToBytes failed:", err) - } - - return buf.Bytes()[buf.Len()-(bits/8):] -} - -// Bytes to number -// -// Attempts to cast a byte slice to a unsigned integer -func BytesToNumber(b []byte) uint64 { - var number uint64 - - // Make sure the buffer is 64bits - data := make([]byte, 8) - data = append(data[:len(b)], b...) - - buf := bytes.NewReader(data) - err := binary.Read(buf, binary.BigEndian, &number) - if err != nil { - fmt.Println("BytesToNumber failed:", err) - } - - return number -} - -// Read variable int -// -// Read a variable length number in big endian byte order -func ReadVarInt(buff []byte) (ret uint64) { - switch l := len(buff); { - case l > 4: - d := LeftPadBytes(buff, 8) - binary.Read(bytes.NewReader(d), binary.BigEndian, &ret) - case l > 2: - var num uint32 - d := LeftPadBytes(buff, 4) - binary.Read(bytes.NewReader(d), binary.BigEndian, &num) - ret = uint64(num) - case l > 1: - var num uint16 - d := LeftPadBytes(buff, 2) - binary.Read(bytes.NewReader(d), binary.BigEndian, &num) - ret = uint64(num) - default: - var num uint8 - binary.Read(bytes.NewReader(buff), binary.BigEndian, &num) - ret = uint64(num) - } - - return -} - -// Binary length -// -// Returns the true binary length of the given number -func BinaryLength(num int) int { - if num == 0 { - return 0 - } - - return 1 + BinaryLength(num>>8) -} - -// Copy bytes -// -// Returns an exact copy of the provided bytes -func CopyBytes(b []byte) (copiedBytes []byte) { - copiedBytes = make([]byte, len(b)) - copy(copiedBytes, b) - - return -} - -func IsHex(str string) bool { - l := len(str) - return l >= 4 && l%2 == 0 && str[0:2] == "0x" -} - -func Bytes2Hex(d []byte) string { - return hex.EncodeToString(d) -} - -func Hex2Bytes(str string) []byte { - h, _ := hex.DecodeString(str) - - return h -} - -func StringToByteFunc(str string, cb func(str string) []byte) (ret []byte) { - if len(str) > 1 && str[0:2] == "0x" && !strings.Contains(str, "\n") { - ret = Hex2Bytes(str[2:]) - } else { - ret = cb(str) - } - - return -} - -func FormatData(data string) []byte { - if len(data) == 0 { - return nil - } - // Simple stupid - d := new(big.Int) - if data[0:1] == "\"" && data[len(data)-1:] == "\"" { - return RightPadBytes([]byte(data[1:len(data)-1]), 32) - } else if len(data) > 1 && data[:2] == "0x" { - d.SetBytes(Hex2Bytes(data[2:])) - } else { - d.SetString(data, 0) - } - - return BigToBytes(d, 256) -} - -func ParseData(data ...interface{}) (ret []byte) { - for _, item := range data { - switch t := item.(type) { - case string: - var str []byte - if IsHex(t) { - str = Hex2Bytes(t[2:]) - } else { - str = []byte(t) - } - - ret = append(ret, RightPadBytes(str, 32)...) - case []byte: - ret = append(ret, LeftPadBytes(t, 32)...) - } - } - - return -} - -func RightPadBytes(slice []byte, l int) []byte { - if l < len(slice) { - return slice - } - - padded := make([]byte, l) - copy(padded[0:len(slice)], slice) - - return padded -} - -func LeftPadBytes(slice []byte, l int) []byte { - if l < len(slice) { - return slice - } - - padded := make([]byte, l) - copy(padded[l-len(slice):], slice) - - return padded -} - -func LeftPadString(str string, l int) string { - if l < len(str) { - return str - } - - zeros := Bytes2Hex(make([]byte, (l-len(str))/2)) - - return zeros + str - -} - -func RightPadString(str string, l int) string { - if l < len(str) { - return str - } - - zeros := Bytes2Hex(make([]byte, (l-len(str))/2)) - - return str + zeros - -} - -func Address(slice []byte) (addr []byte) { - if len(slice) < 20 { - addr = LeftPadBytes(slice, 20) - } else if len(slice) > 20 { - addr = slice[len(slice)-20:] - } else { - addr = slice - } - - addr = CopyBytes(addr) - - return -} - -func ByteSliceToInterface(slice [][]byte) (ret []interface{}) { - for _, i := range slice { - ret = append(ret, i) - } - - return -} diff --git a/ethutil/bytes_test.go b/ethutil/bytes_test.go deleted file mode 100644 index 179a8c7ef..000000000 --- a/ethutil/bytes_test.go +++ /dev/null @@ -1,193 +0,0 @@ -package ethutil - -import ( - checker "gopkg.in/check.v1" -) - -type BytesSuite struct{} - -var _ = checker.Suite(&BytesSuite{}) - -func (s *BytesSuite) TestByteString(c *checker.C) { - var data Bytes - data = []byte{102, 111, 111} - exp := "foo" - res := data.String() - - c.Assert(res, checker.Equals, exp) -} - -/* -func (s *BytesSuite) TestDeleteFromByteSlice(c *checker.C) { - data := []byte{1, 2, 3, 4} - slice := []byte{1, 2, 3, 4} - exp := []byte{1, 4} - res := DeleteFromByteSlice(data, slice) - - c.Assert(res, checker.DeepEquals, exp) -} - -*/ -func (s *BytesSuite) TestNumberToBytes(c *checker.C) { - // data1 := int(1) - // res1 := NumberToBytes(data1, 16) - // c.Check(res1, checker.Panics) - - var data2 float64 = 3.141592653 - exp2 := []byte{0xe9, 0x38} - res2 := NumberToBytes(data2, 16) - c.Assert(res2, checker.DeepEquals, exp2) -} - -func (s *BytesSuite) TestBytesToNumber(c *checker.C) { - datasmall := []byte{0xe9, 0x38, 0xe9, 0x38} - datalarge := []byte{0xe9, 0x38, 0xe9, 0x38, 0xe9, 0x38, 0xe9, 0x38} - - var expsmall uint64 = 0xe938e938 - var explarge uint64 = 0x0 - - ressmall := BytesToNumber(datasmall) - reslarge := BytesToNumber(datalarge) - - c.Assert(ressmall, checker.Equals, expsmall) - c.Assert(reslarge, checker.Equals, explarge) - -} - -func (s *BytesSuite) TestReadVarInt(c *checker.C) { - data8 := []byte{1, 2, 3, 4, 5, 6, 7, 8} - data4 := []byte{1, 2, 3, 4} - data2 := []byte{1, 2} - data1 := []byte{1} - - exp8 := uint64(72623859790382856) - exp4 := uint64(16909060) - exp2 := uint64(258) - exp1 := uint64(1) - - res8 := ReadVarInt(data8) - res4 := ReadVarInt(data4) - res2 := ReadVarInt(data2) - res1 := ReadVarInt(data1) - - c.Assert(res8, checker.Equals, exp8) - c.Assert(res4, checker.Equals, exp4) - c.Assert(res2, checker.Equals, exp2) - c.Assert(res1, checker.Equals, exp1) -} - -func (s *BytesSuite) TestBinaryLength(c *checker.C) { - data1 := 0 - data2 := 920987656789 - - exp1 := 0 - exp2 := 5 - - res1 := BinaryLength(data1) - res2 := BinaryLength(data2) - - c.Assert(res1, checker.Equals, exp1) - c.Assert(res2, checker.Equals, exp2) -} - -func (s *BytesSuite) TestCopyBytes(c *checker.C) { - data1 := []byte{1, 2, 3, 4} - exp1 := []byte{1, 2, 3, 4} - res1 := CopyBytes(data1) - c.Assert(res1, checker.DeepEquals, exp1) -} - -func (s *BytesSuite) TestIsHex(c *checker.C) { - data1 := "a9e67e" - exp1 := false - res1 := IsHex(data1) - c.Assert(res1, checker.DeepEquals, exp1) - - data2 := "0xa9e67e00" - exp2 := true - res2 := IsHex(data2) - c.Assert(res2, checker.DeepEquals, exp2) - -} - -func (s *BytesSuite) TestParseDataString(c *checker.C) { - res1 := ParseData("hello", "world", "0x0106") - data := "68656c6c6f000000000000000000000000000000000000000000000000000000776f726c640000000000000000000000000000000000000000000000000000000106000000000000000000000000000000000000000000000000000000000000" - exp1 := Hex2Bytes(data) - c.Assert(res1, checker.DeepEquals, exp1) -} - -func (s *BytesSuite) TestParseDataBytes(c *checker.C) { - data1 := []byte{232, 212, 165, 16, 0} - exp1 := []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 232, 212, 165, 16, 0} - - res1 := ParseData(data1) - c.Assert(res1, checker.DeepEquals, exp1) - -} - -func (s *BytesSuite) TestLeftPadBytes(c *checker.C) { - val1 := []byte{1, 2, 3, 4} - exp1 := []byte{0, 0, 0, 0, 1, 2, 3, 4} - - res1 := LeftPadBytes(val1, 8) - res2 := LeftPadBytes(val1, 2) - - c.Assert(res1, checker.DeepEquals, exp1) - c.Assert(res2, checker.DeepEquals, val1) -} - -func (s *BytesSuite) TestFormatData(c *checker.C) { - data1 := "" - data2 := "0xa9e67e00" - data3 := "a9e67e" - data4 := "\"a9e67e00\"" - - // exp1 := []byte{} - exp2 := []byte{00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 0xa9, 0xe6, 0x7e, 00} - exp3 := []byte{00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00} - exp4 := []byte{0x61, 0x39, 0x65, 0x36, 0x37, 0x65, 0x30, 0x30, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00} - - res1 := FormatData(data1) - res2 := FormatData(data2) - res3 := FormatData(data3) - res4 := FormatData(data4) - - c.Assert(res1, checker.IsNil) - c.Assert(res2, checker.DeepEquals, exp2) - c.Assert(res3, checker.DeepEquals, exp3) - c.Assert(res4, checker.DeepEquals, exp4) -} - -func (s *BytesSuite) TestRightPadBytes(c *checker.C) { - val := []byte{1, 2, 3, 4} - exp := []byte{1, 2, 3, 4, 0, 0, 0, 0} - - resstd := RightPadBytes(val, 8) - resshrt := RightPadBytes(val, 2) - - c.Assert(resstd, checker.DeepEquals, exp) - c.Assert(resshrt, checker.DeepEquals, val) -} - -func (s *BytesSuite) TestLeftPadString(c *checker.C) { - val := "test" - exp := "\x30\x30\x30\x30" + val - - resstd := LeftPadString(val, 8) - resshrt := LeftPadString(val, 2) - - c.Assert(resstd, checker.Equals, exp) - c.Assert(resshrt, checker.Equals, val) -} - -func (s *BytesSuite) TestRightPadString(c *checker.C) { - val := "test" - exp := val + "\x30\x30\x30\x30" - - resstd := RightPadString(val, 8) - resshrt := RightPadString(val, 2) - - c.Assert(resstd, checker.Equals, exp) - c.Assert(resshrt, checker.Equals, val) -} diff --git a/ethutil/common.go b/ethutil/common.go deleted file mode 100644 index 29854c882..000000000 --- a/ethutil/common.go +++ /dev/null @@ -1,165 +0,0 @@ -package ethutil - -import ( - "fmt" - "math/big" - "os" - "os/user" - "path" - "path/filepath" - "runtime" - "time" - - "github.com/kardianos/osext" -) - -// MakeName creates a node name that follows the ethereum convention -// for such names. It adds the operation system name and Go runtime version -// the name. -func MakeName(name, version string) string { - return fmt.Sprintf("%s/v%s/%s/%s", name, version, runtime.GOOS, runtime.Version()) -} - -func DefaultAssetPath() string { - var assetPath string - pwd, _ := os.Getwd() - srcdir := path.Join(os.Getenv("GOPATH"), "src", "github.com", "ethereum", "go-ethereum", "cmd", "mist") - - // If the current working directory is the go-ethereum dir - // assume a debug build and use the source directory as - // asset directory. - if pwd == srcdir { - assetPath = path.Join(pwd, "assets") - } else { - switch runtime.GOOS { - case "darwin": - // Get Binary Directory - exedir, _ := osext.ExecutableFolder() - assetPath = filepath.Join(exedir, "../Resources") - case "linux": - assetPath = "/usr/share/mist" - case "windows": - assetPath = "./assets" - default: - assetPath = "." - } - } - - // Check if the assetPath exists. If not, try the source directory - // This happens when binary is run from outside cmd/mist directory - if _, err := os.Stat(assetPath); os.IsNotExist(err) { - assetPath = path.Join(srcdir, "assets") - } - - return assetPath -} - -func DefaultDataDir() string { - usr, _ := user.Current() - if runtime.GOOS == "darwin" { - return path.Join(usr.HomeDir, "Library/Ethereum") - } else if runtime.GOOS == "windows" { - return path.Join(usr.HomeDir, "AppData/Roaming/Ethereum") - } else { - return path.Join(usr.HomeDir, ".ethereum") - } -} - -func FromHex(s string) []byte { - if len(s) > 1 { - if s[0:2] == "0x" { - s = s[2:] - } - if len(s)%2 == 1 { - s = "0" + s - } - return Hex2Bytes(s) - } - return nil -} -func IsWindows() bool { - return runtime.GOOS == "windows" -} - -func WindonizePath(path string) string { - if string(path[0]) == "/" && IsWindows() { - path = path[1:] - } - return path -} - -// The different number of units -var ( - Douglas = BigPow(10, 42) - Einstein = BigPow(10, 21) - Ether = BigPow(10, 18) - Finney = BigPow(10, 15) - Szabo = BigPow(10, 12) - Shannon = BigPow(10, 9) - Babbage = BigPow(10, 6) - Ada = BigPow(10, 3) - Wei = big.NewInt(1) -) - -// -// Currency to string -// Returns a string representing a human readable format -func CurrencyToString(num *big.Int) string { - var ( - fin *big.Int = num - denom string = "Wei" - ) - - switch { - case num.Cmp(Douglas) >= 0: - fin = new(big.Int).Div(num, Douglas) - denom = "Douglas" - case num.Cmp(Einstein) >= 0: - fin = new(big.Int).Div(num, Einstein) - denom = "Einstein" - case num.Cmp(Ether) >= 0: - fin = new(big.Int).Div(num, Ether) - denom = "Ether" - case num.Cmp(Finney) >= 0: - fin = new(big.Int).Div(num, Finney) - denom = "Finney" - case num.Cmp(Szabo) >= 0: - fin = new(big.Int).Div(num, Szabo) - denom = "Szabo" - case num.Cmp(Shannon) >= 0: - fin = new(big.Int).Div(num, Shannon) - denom = "Shannon" - case num.Cmp(Babbage) >= 0: - fin = new(big.Int).Div(num, Babbage) - denom = "Babbage" - case num.Cmp(Ada) >= 0: - fin = new(big.Int).Div(num, Ada) - denom = "Ada" - } - - // TODO add comment clarifying expected behavior - if len(fin.String()) > 5 { - return fmt.Sprintf("%sE%d %s", fin.String()[0:5], len(fin.String())-5, denom) - } - - return fmt.Sprintf("%v %s", fin, denom) -} - -// Common big integers often used -var ( - Big1 = big.NewInt(1) - Big2 = big.NewInt(2) - Big3 = big.NewInt(3) - Big0 = big.NewInt(0) - BigTrue = Big1 - BigFalse = Big0 - Big32 = big.NewInt(32) - Big256 = big.NewInt(0xff) - Big257 = big.NewInt(257) -) - -func Bench(pre string, cb func()) { - start := time.Now() - cb() - fmt.Println(pre, ": took:", time.Since(start)) -} diff --git a/ethutil/common_test.go b/ethutil/common_test.go deleted file mode 100644 index 20064b1e7..000000000 --- a/ethutil/common_test.go +++ /dev/null @@ -1,89 +0,0 @@ -package ethutil - -import ( - "bytes" - "math/big" - "os" - "testing" - - checker "gopkg.in/check.v1" -) - -type CommonSuite struct{} - -var _ = checker.Suite(&CommonSuite{}) - -func (s *CommonSuite) TestOS(c *checker.C) { - expwin := (os.PathSeparator == '\\' && os.PathListSeparator == ';') - res := IsWindows() - - if !expwin { - c.Assert(res, checker.Equals, expwin, checker.Commentf("IsWindows is", res, "but path is", os.PathSeparator)) - } else { - c.Assert(res, checker.Not(checker.Equals), expwin, checker.Commentf("IsWindows is", res, "but path is", os.PathSeparator)) - } -} - -func (s *CommonSuite) TestWindonziePath(c *checker.C) { - iswindowspath := os.PathSeparator == '\\' - path := "/opt/eth/test/file.ext" - res := WindonizePath(path) - ressep := string(res[0]) - - if !iswindowspath { - c.Assert(ressep, checker.Equals, "/") - } else { - c.Assert(ressep, checker.Not(checker.Equals), "/") - } -} - -func (s *CommonSuite) TestCommon(c *checker.C) { - douglas := CurrencyToString(BigPow(10, 43)) - einstein := CurrencyToString(BigPow(10, 22)) - ether := CurrencyToString(BigPow(10, 19)) - finney := CurrencyToString(BigPow(10, 16)) - szabo := CurrencyToString(BigPow(10, 13)) - shannon := CurrencyToString(BigPow(10, 10)) - babbage := CurrencyToString(BigPow(10, 7)) - ada := CurrencyToString(BigPow(10, 4)) - wei := CurrencyToString(big.NewInt(10)) - - c.Assert(douglas, checker.Equals, "10 Douglas") - c.Assert(einstein, checker.Equals, "10 Einstein") - c.Assert(ether, checker.Equals, "10 Ether") - c.Assert(finney, checker.Equals, "10 Finney") - c.Assert(szabo, checker.Equals, "10 Szabo") - c.Assert(shannon, checker.Equals, "10 Shannon") - c.Assert(babbage, checker.Equals, "10 Babbage") - c.Assert(ada, checker.Equals, "10 Ada") - c.Assert(wei, checker.Equals, "10 Wei") -} - -func (s *CommonSuite) TestLarge(c *checker.C) { - douglaslarge := CurrencyToString(BigPow(100000000, 43)) - adalarge := CurrencyToString(BigPow(100000000, 4)) - weilarge := CurrencyToString(big.NewInt(100000000)) - - c.Assert(douglaslarge, checker.Equals, "10000E298 Douglas") - c.Assert(adalarge, checker.Equals, "10000E7 Einstein") - c.Assert(weilarge, checker.Equals, "100 Babbage") -} - -//fromHex -func TestFromHex(t *testing.T) { - input := "0x01" - expected := []byte{1} - result := FromHex(input) - if bytes.Compare(expected, result) != 0 { - t.Errorf("Expected % x got % x", expected, result) - } -} - -func TestFromHexOddLength(t *testing.T) { - input := "0x1" - expected := []byte{1} - result := FromHex(input) - if bytes.Compare(expected, result) != 0 { - t.Errorf("Expected % x got % x", expected, result) - } -} diff --git a/ethutil/config.go b/ethutil/config.go deleted file mode 100644 index c45c310ce..000000000 --- a/ethutil/config.go +++ /dev/null @@ -1,67 +0,0 @@ -package ethutil - -import ( - "flag" - "fmt" - "os" - - "github.com/rakyll/globalconf" -) - -// Config struct -type ConfigManager struct { - ExecPath string - Debug bool - Diff bool - DiffType string - Paranoia bool - VmType int - - conf *globalconf.GlobalConf -} - -// Read config -// -// Initialize Config from Config File -func ReadConfig(ConfigFile string, Datadir string, EnvPrefix string) *ConfigManager { - if !FileExist(ConfigFile) { - // create ConfigFile if it does not exist, otherwise - // globalconf will panic when trying to persist flags. - fmt.Printf("config file '%s' doesn't exist, creating it\n", ConfigFile) - os.Create(ConfigFile) - } - g, err := globalconf.NewWithOptions(&globalconf.Options{ - Filename: ConfigFile, - EnvPrefix: EnvPrefix, - }) - if err != nil { - fmt.Println(err) - } else { - g.ParseAll() - } - cfg := &ConfigManager{ExecPath: Datadir, Debug: true, conf: g, Paranoia: true} - return cfg -} - -// provides persistence for flags -func (c *ConfigManager) Save(key string, value interface{}) { - f := &flag.Flag{Name: key, Value: newConfValue(value)} - c.conf.Set("", f) -} - -func (c *ConfigManager) Delete(key string) { - c.conf.Delete("", key) -} - -// private type implementing flag.Value -type confValue struct { - value string -} - -// generic constructor to allow persising non-string values directly -func newConfValue(value interface{}) *confValue { - return &confValue{fmt.Sprintf("%v", value)} -} - -func (self confValue) String() string { return self.value } -func (self confValue) Set(s string) error { self.value = s; return nil } diff --git a/ethutil/db.go b/ethutil/db.go deleted file mode 100644 index e02a80fca..000000000 --- a/ethutil/db.go +++ /dev/null @@ -1,12 +0,0 @@ -package ethutil - -// Database interface -type Database interface { - Put(key []byte, value []byte) - Get(key []byte) ([]byte, error) - //GetKeys() []*Key - Delete(key []byte) error - LastKnownTD() []byte - Close() - Print() -} diff --git a/ethutil/list.go b/ethutil/list.go deleted file mode 100644 index db276f1e3..000000000 --- a/ethutil/list.go +++ /dev/null @@ -1,81 +0,0 @@ -package ethutil - -import ( - "encoding/json" - "reflect" - "sync" -) - -// The list type is an anonymous slice handler which can be used -// for containing any slice type to use in an environment which -// does not support slice types (e.g., JavaScript, QML) -type List struct { - mut sync.Mutex - val interface{} - list reflect.Value - Length int -} - -// Initialise a new list. Panics if non-slice type is given. -func NewList(t interface{}) *List { - list := reflect.ValueOf(t) - if list.Kind() != reflect.Slice { - panic("list container initialized with a non-slice type") - } - - return &List{sync.Mutex{}, t, list, list.Len()} -} - -func EmptyList() *List { - return NewList([]interface{}{}) -} - -// Get N element from the embedded slice. Returns nil if OOB. -func (self *List) Get(i int) interface{} { - if self.list.Len() > i { - self.mut.Lock() - defer self.mut.Unlock() - - i := self.list.Index(i).Interface() - - return i - } - - return nil -} - -func (self *List) GetAsJson(i int) interface{} { - e := self.Get(i) - - r, _ := json.Marshal(e) - - return string(r) -} - -// Appends value at the end of the slice. Panics when incompatible value -// is given. -func (self *List) Append(v interface{}) { - self.mut.Lock() - defer self.mut.Unlock() - - self.list = reflect.Append(self.list, reflect.ValueOf(v)) - self.Length = self.list.Len() -} - -// Returns the underlying slice as interface. -func (self *List) Interface() interface{} { - return self.list.Interface() -} - -// For JavaScript <3 -func (self *List) ToJSON() string { - // make(T, 0) != nil - list := make([]interface{}, 0) - for i := 0; i < self.Length; i++ { - list = append(list, self.Get(i)) - } - - data, _ := json.Marshal(list) - - return string(data) -} diff --git a/ethutil/main_test.go b/ethutil/main_test.go deleted file mode 100644 index fd4278ce7..000000000 --- a/ethutil/main_test.go +++ /dev/null @@ -1,9 +0,0 @@ -package ethutil - -import ( - "testing" - - checker "gopkg.in/check.v1" -) - -func Test(t *testing.T) { checker.TestingT(t) } diff --git a/ethutil/math/dist.go b/ethutil/math/dist.go deleted file mode 100644 index 262aa8591..000000000 --- a/ethutil/math/dist.go +++ /dev/null @@ -1,80 +0,0 @@ -package math - -import ( - "math/big" - "sort" - - "github.com/ethereum/go-ethereum/ethutil" -) - -type Summer interface { - Sum(i int) *big.Int - Len() int -} - -func Sum(slice Summer) (sum *big.Int) { - sum = new(big.Int) - - for i := 0; i < slice.Len(); i++ { - sum.Add(sum, slice.Sum(i)) - } - return -} - -type Vector struct { - Gas, Price *big.Int -} - -type VectorsBy func(v1, v2 Vector) bool - -func (self VectorsBy) Sort(vectors []Vector) { - bs := vectorSorter{ - vectors: vectors, - by: self, - } - sort.Sort(bs) -} - -type vectorSorter struct { - vectors []Vector - by func(v1, v2 Vector) bool -} - -func (v vectorSorter) Len() int { return len(v.vectors) } -func (v vectorSorter) Less(i, j int) bool { return v.by(v.vectors[i], v.vectors[j]) } -func (v vectorSorter) Swap(i, j int) { v.vectors[i], v.vectors[j] = v.vectors[j], v.vectors[i] } - -func PriceSort(v1, v2 Vector) bool { return v1.Price.Cmp(v2.Price) < 0 } -func GasSort(v1, v2 Vector) bool { return v1.Gas.Cmp(v2.Gas) < 0 } - -type vectorSummer struct { - vectors []Vector - by func(v Vector) *big.Int -} - -type VectorSum func(v Vector) *big.Int - -func (v VectorSum) Sum(vectors []Vector) *big.Int { - vs := vectorSummer{ - vectors: vectors, - by: v, - } - return Sum(vs) -} - -func (v vectorSummer) Len() int { return len(v.vectors) } -func (v vectorSummer) Sum(i int) *big.Int { return v.by(v.vectors[i]) } - -func GasSum(v Vector) *big.Int { return v.Gas } - -var etherInWei = new(big.Rat).SetInt(ethutil.String2Big("1000000000000000000")) - -func GasPrice(bp, gl, ep *big.Int) *big.Int { - BP := new(big.Rat).SetInt(bp) - GL := new(big.Rat).SetInt(gl) - EP := new(big.Rat).SetInt(ep) - GP := new(big.Rat).Quo(BP, GL) - GP = GP.Quo(GP, EP) - - return GP.Mul(GP, etherInWei).Num() -} diff --git a/ethutil/math/dist_test.go b/ethutil/math/dist_test.go deleted file mode 100644 index 90e302f44..000000000 --- a/ethutil/math/dist_test.go +++ /dev/null @@ -1,66 +0,0 @@ -package math - -import ( - "fmt" - "math/big" - "testing" -) - -type summer struct { - numbers []*big.Int -} - -func (s summer) Len() int { return len(s.numbers) } -func (s summer) Sum(i int) *big.Int { - return s.numbers[i] -} - -func TestSum(t *testing.T) { - summer := summer{numbers: []*big.Int{big.NewInt(1), big.NewInt(2), big.NewInt(3)}} - sum := Sum(summer) - if sum.Cmp(big.NewInt(6)) != 0 { - t.Errorf("not 6", sum) - } -} - -func TestDist(t *testing.T) { - var vectors = []Vector{ - Vector{big.NewInt(1000), big.NewInt(1234)}, - Vector{big.NewInt(500), big.NewInt(10023)}, - Vector{big.NewInt(1034), big.NewInt(1987)}, - Vector{big.NewInt(1034), big.NewInt(1987)}, - Vector{big.NewInt(8983), big.NewInt(1977)}, - Vector{big.NewInt(98382), big.NewInt(1887)}, - Vector{big.NewInt(12398), big.NewInt(1287)}, - Vector{big.NewInt(12398), big.NewInt(1487)}, - Vector{big.NewInt(12398), big.NewInt(1987)}, - Vector{big.NewInt(12398), big.NewInt(128)}, - Vector{big.NewInt(12398), big.NewInt(1987)}, - Vector{big.NewInt(1398), big.NewInt(187)}, - Vector{big.NewInt(12328), big.NewInt(1927)}, - Vector{big.NewInt(12398), big.NewInt(1987)}, - Vector{big.NewInt(22398), big.NewInt(1287)}, - Vector{big.NewInt(1370), big.NewInt(1981)}, - Vector{big.NewInt(12398), big.NewInt(1957)}, - Vector{big.NewInt(42198), big.NewInt(1987)}, - } - - VectorsBy(GasSort).Sort(vectors) - fmt.Println(vectors) - - BP := big.NewInt(15) - GL := big.NewInt(1000000) - EP := big.NewInt(100) - fmt.Println("BP", BP, "GL", GL, "EP", EP) - GP := GasPrice(BP, GL, EP) - fmt.Println("GP =", GP, "Wei per GU") - - S := len(vectors) / 4 - fmt.Println("L", len(vectors), "S", S) - for i := 1; i <= S*4; i += S { - fmt.Printf("T%d = %v\n", i, vectors[i]) - } - - g := VectorSum(GasSum).Sum(vectors) - fmt.Printf("G = ∑g* (%v)\n", g) -} diff --git a/ethutil/natspec/natspec.go b/ethutil/natspec/natspec.go deleted file mode 100644 index 793bf59ae..000000000 --- a/ethutil/natspec/natspec.go +++ /dev/null @@ -1,63 +0,0 @@ -package natspec - -import ( - "fmt" - "github.com/obscuren/otto" -) - -type NatSpec struct { - jsvm *otto.Otto -} - -// TODO: should initialise with abi and userdoc jsons -func New() (self *NatSpec, err error) { - - self = new(NatSpec) - self.jsvm = otto.New() - - _, err = self.jsvm.Run(natspecJS) - if err != nil { - return - } - _, err = self.jsvm.Run("var natspec = require('natspec');") - if err != nil { - return - } - - return -} - -func (self *NatSpec) Notice(transaction, abi, method, expression string) (string, error) { - var err error - if _, err = self.jsvm.Run("var transaction = " + transaction + ";"); err != nil { - return "", fmt.Errorf("natspec.js error setting transaction: %v", err) - } - - if _, err = self.jsvm.Run("var abi = " + abi + ";"); err != nil { - return "", fmt.Errorf("natspec.js error setting abi: %v", err) - } - - if _, err = self.jsvm.Run("var method = '" + method + "';"); err != nil { - return "", fmt.Errorf("natspec.js error setting method: %v", err) - } - - if _, err = self.jsvm.Run("var expression = \"" + expression + "\";"); err != nil { - return "", fmt.Errorf("natspec.js error setting expression: %v", err) - } - - self.jsvm.Run("var call = {method: method,abi: abi,transaction: transaction};") - value, err := self.jsvm.Run("natspec.evaluateExpression(expression, call);") - if err != nil { - return "", fmt.Errorf("natspec.js error evaluating expression: %v", err) - } - evalError := "Natspec evaluation failed, wrong input params" - if value.String() == evalError { - return "", fmt.Errorf("natspec.js error evaluating expression: wrong input params in expression '%s'", expression) - } - if len(value.String()) == 0 { - return "", fmt.Errorf("natspec.js error evaluating expression") - } - - return value.String(), nil - -} diff --git a/ethutil/natspec/natspec_js.go b/ethutil/natspec/natspec_js.go deleted file mode 100644 index 96d8204fb..000000000 --- a/ethutil/natspec/natspec_js.go +++ /dev/null @@ -1,4 +0,0 @@ -package natspec - -const natspecJS = `require=function t(e,n,r){function i(f,u){if(!n[f]){if(!e[f]){var s="function"==typeof require&&require;if(!u&&s)return s(f,!0);if(o)return o(f,!0);var c=new Error("Cannot find module '"+f+"'");throw c.code="MODULE_NOT_FOUND",c}var a=n[f]={exports:{}};e[f][0].call(a.exports,function(t){var n=e[f][1][t];return i(n?n:t)},a,a.exports,t,e,n,r)}return n[f].exports}for(var o="function"==typeof require&&require,f=0;fv;v++)d.push(g(e.slice(0,s))),e=e.slice(s);n.push(d)}else r.prefixedType("string")(t[c].type)?(a=a.slice(s),n.push(g(e.slice(0,s))),e=e.slice(s)):(n.push(g(e.slice(0,s))),e=e.slice(s))}),n},g=function(t){var e={};return t.forEach(function(t){var r=n.extractDisplayName(t.name),i=n.extractTypeName(t.name),o=function(){var e=Array.prototype.slice.call(arguments);return a(t.inputs,e)};void 0===e[r]&&(e[r]=o),e[r][i]=o}),e},m=function(t){var e={};return t.forEach(function(t){var r=n.extractDisplayName(t.name),i=n.extractTypeName(t.name),o=function(e){return h(t.outputs,e)};void 0===e[r]&&(e[r]=o),e[r][i]=o}),e};e.exports={inputParser:g,outputParser:m,formatInput:a,formatOutput:h}},{"./const":4,"./formatters":5,"./types":6,"./utils":7}],4:[function(t,e){(function(n){if("build"!==n.env.NODE_ENV)var r=t("bignumber.js");var i=["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:i,ETH_BIGNUMBER_ROUNDING_MODE:{ROUNDING_MODE:r.ROUND_DOWN},ETH_POLLING_TIMEOUT:1e3}}).call(this,t("_process"))},{_process:2,"bignumber.js":8}],5:[function(t,e){(function(n){if("build"!==n.env.NODE_ENV)var r=t("bignumber.js");var i=t("./utils"),o=t("./const"),f=function(t,e,n){return new Array(e-t.length+1).join(n?n:"0")+t},u=function(t){var e=2*o.ETH_PADDING;return t instanceof r||"number"==typeof t?("number"==typeof t&&(t=new r(t)),r.config(o.ETH_BIGNUMBER_ROUNDING_MODE),t=t.round(),t.lessThan(0)&&(t=new r("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",16).plus(t).plus(1)),t=t.toString(16)):t=0===t.indexOf("0x")?t.substr(2):"string"==typeof t?u(new r(t)):(+t).toString(16),f(t,e)},s=function(t){return i.fromAscii(t,o.ETH_PADDING).substr(2)},c=function(t){return"000000000000000000000000000000000000000000000000000000000000000"+(t?"1":"0")},a=function(t){return u(new r(t).times(new r(2).pow(128)))},l=function(t){return"1"===new r(t.substr(0,1),16).toString(2).substr(0,1)},p=function(t){return t=t||"0",l(t)?new r(t,16).minus(new r("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",16)).minus(1):new r(t,16)},h=function(t){return t=t||"0",new r(t,16)},g=function(t){return p(t).dividedBy(new r(2).pow(128))},m=function(t){return h(t).dividedBy(new r(2).pow(128))},d=function(t){return"0x"+t},v=function(t){return"0000000000000000000000000000000000000000000000000000000000000001"===t?!0:!1},w=function(t){return i.toAscii(t)},y=function(t){return"0x"+t.slice(t.length-40,t.length)};e.exports={formatInputInt:u,formatInputString:s,formatInputBool:c,formatInputReal:a,formatOutputInt:p,formatOutputUInt:h,formatOutputReal:g,formatOutputUReal:m,formatOutputHash:d,formatOutputBool:v,formatOutputString:w,formatOutputAddress:y}}).call(this,t("_process"))},{"./const":4,"./utils":7,_process:2,"bignumber.js":8}],6:[function(t,e){var n=t("./formatters"),r=function(t){return function(e){return 0===e.indexOf(t)}},i=function(t){return function(e){return t===e}},o=function(){return[{type:r("uint"),format:n.formatInputInt},{type:r("int"),format:n.formatInputInt},{type:r("hash"),format:n.formatInputInt},{type:r("string"),format:n.formatInputString},{type:r("real"),format:n.formatInputReal},{type:r("ureal"),format:n.formatInputReal},{type:i("address"),format:n.formatInputInt},{type:i("bool"),format:n.formatInputBool}]},f=function(){return[{type:r("uint"),format:n.formatOutputUInt},{type:r("int"),format:n.formatOutputInt},{type:r("hash"),format:n.formatOutputHash},{type:r("string"),format:n.formatOutputString},{type:r("real"),format:n.formatOutputReal},{type:r("ureal"),format:n.formatOutputUReal},{type:i("address"),format:n.formatOutputAddress},{type:i("bool"),format:n.formatOutputBool}]};e.exports={prefixedType:r,namedType:i,inputTypes:o,outputTypes:f}},{"./formatters":5}],7:[function(t,e){var n=t("./const"),r=function(t,e){for(var n=!1,r=0;rn;n+=2){var i=parseInt(t.substr(n,2),16);if(0===i)break;e+=String.fromCharCode(i)}return e},o=function(t){for(var e="",n=0;n3e3&&rr?"i":"").test(c))return m(a,c,u,r);u?(a.s=0>1/t?(c=c.slice(1),-1):1,$&&c.replace(/^0\.0*|\./,"").length>15&&U(L,O,t),u=!1):a.s=45===c.charCodeAt(0)?(c=c.slice(1),-1):1,c=n(c,10,r,a.s)}else{if(t instanceof e)return a.s=t.s,a.e=t.e,a.c=(t=t.c)?t.slice():t,void(L=0);if((u="number"==typeof t)&&0*t==0){if(a.s=0>1/t?(t=-t,-1):1,t===~~t){for(o=0,f=t;f>=10;f/=10,o++);return a.e=o,a.c=[t],void(L=0)}c=t+""}else{if(!d.test(c=t+""))return m(a,c,u);a.s=45===c.charCodeAt(0)?(c=c.slice(1),-1):1}}for((o=c.indexOf("."))>-1&&(c=c.replace(".","")),(f=c.search(/e/i))>0?(0>o&&(o=f),o+=+c.slice(f+1),c=c.substring(0,f)):0>o&&(o=c.length),f=0;48===c.charCodeAt(f);f++);for(s=c.length;48===c.charCodeAt(--s););if(c=c.slice(f,s+1))if(s=c.length,u&&$&&s>15&&U(L,O,a.s*t),o=o-f-1,o>q)a.c=a.e=null;else if(k>o)a.c=[a.e=0];else{if(a.e=o,a.c=[],f=(o+1)%I,0>o&&(f+=I),s>f){for(f&&a.c.push(+c.slice(0,f)),s-=I;s>f;)a.c.push(+c.slice(f,f+=I));c=c.slice(f),f=I-c.length}else f-=s;for(;f--;c+="0");a.c.push(+c)}else a.c=[a.e=0];L=0}function n(t,n,r,i){var f,u,s,a,p,h,g,m=t.indexOf("."),d=B,v=H;for(37>r&&(t=t.toLowerCase()),m>=0&&(s=Y,Y=0,t=t.replace(".",""),g=new e(r),p=g.pow(t.length-m),Y=s,g.c=c(l(o(p.c),p.e),10,n),g.e=g.c.length),h=c(t,r,n),u=s=h.length;0==h[--s];h.pop());if(!h[0])return"0";if(0>m?--u:(p.c=h,p.e=u,p.s=i,p=G(p,g,d,v,n),h=p.c,a=p.r,u=p.e),f=u+d+1,m=h[f],s=n/2,a=a||0>f||null!=h[f+1],a=4>v?(null!=m||a)&&(0==v||v==(p.s<0?3:2)):m>s||m==s&&(4==v||a||6==v&&1&h[f-1]||v==(p.s<0?8:7)),1>f||!h[0])t=a?l("1",-d):"0";else{if(h.length=f,a)for(--n;++h[--f]>n;)h[f]=0,f||(++u,h.unshift(1));for(s=h.length;!h[--s];);for(m=0,t="";s>=m;t+=N.charAt(h[m++]));t=l(t,u)}return t}function h(t,n,r,i){var f,u,s,c,p;if(r=null!=r&&z(r,0,8,i,b)?0|r:H,!t.c)return t.toString();if(f=t.c[0],s=t.e,null==n)p=o(t.c),p=19==i||24==i&&C>=s?a(p,s):l(p,s);else if(t=F(new e(t),n,r),u=t.e,p=o(t.c),c=p.length,19==i||24==i&&(u>=n||C>=u)){for(;n>c;p+="0",c++);p=a(p,u)}else if(n-=s,p=l(p,u),u+1>c){if(--n>0)for(p+=".";n--;p+="0");}else if(n+=u-c,n>0)for(u+1==c&&(p+=".");n--;p+="0");return t.s<0&&f?"-"+p:p}function S(t,n){var r,i,o=0;for(s(t[0])&&(t=t[0]),r=new e(t[0]);++ot||t>n||t!=p(t))&&U(r,(i||"decimal places")+(e>t||t>n?" out of range":" not an integer"),t),!0}function R(t,e,n){for(var r=1,i=e.length;!e[--i];e.pop());for(i=e[0];i>=10;i/=10,r++);return(n=r+n*I-1)>q?t.c=t.e=null:k>n?t.c=[t.e=0]:(t.e=n,t.c=e),t}function U(t,e,n){var r=new Error(["new BigNumber","cmp","config","div","divToInt","eq","gt","gte","lt","lte","minus","mod","plus","precision","random","round","shift","times","toDigits","toExponential","toFixed","toFormat","toFraction","pow","toPrecision","toString","BigNumber"][t]+"() "+e+": "+n);throw r.name="BigNumber Error",L=0,r}function F(t,e,n,r){var i,o,f,u,s,c,a,l=t.c,p=_;if(l){t:{for(i=1,u=l[0];u>=10;u/=10,i++);if(o=e-i,0>o)o+=I,f=e,s=l[c=0],a=s/p[i-f-1]%10|0;else if(c=v((o+1)/I),c>=l.length){if(!r)break t;for(;l.length<=c;l.push(0));s=a=0,i=1,o%=I,f=o-I+1}else{for(s=u=l[c],i=1;u>=10;u/=10,i++);o%=I,f=o-I+i,a=0>f?0:s/p[i-f-1]%10|0}if(r=r||0>e||null!=l[c+1]||(0>f?s:s%p[i-f-1]),r=4>n?(a||r)&&(0==n||n==(t.s<0?3:2)):a>5||5==a&&(4==n||r||6==n&&(o>0?f>0?s/p[i-f]:0:l[c-1])%10&1||n==(t.s<0?8:7)),1>e||!l[0])return l.length=0,r?(e-=t.e+1,l[0]=p[e%I],t.e=-e||0):l[0]=t.e=0,t;if(0==o?(l.length=c,u=1,c--):(l.length=c+1,u=p[I-o],l[c]=f>0?w(s/p[i-f]%p[f])*u:0),r)for(;;){if(0==c){for(o=1,f=l[0];f>=10;f/=10,o++);for(f=l[0]+=u,u=1;f>=10;f/=10,u++);o!=u&&(t.e++,l[0]==E&&(l[0]=1));break}if(l[c]+=u,l[c]!=E)break;l[c--]=0,u=1}for(o=l.length;0===l[--o];l.pop());}t.e>q?t.c=t.e=null:t.en?null!=(t=i[n++]):void 0};return f(e="DECIMAL_PLACES")&&z(t,0,D,2,e)&&(B=0|t),r[e]=B,f(e="ROUNDING_MODE")&&z(t,0,8,2,e)&&(H=0|t),r[e]=H,f(e="EXPONENTIAL_AT")&&(s(t)?z(t[0],-D,0,2,e)&&z(t[1],0,D,2,e)&&(C=0|t[0],j=0|t[1]):z(t,-D,D,2,e)&&(C=-(j=0|(0>t?-t:t)))),r[e]=[C,j],f(e="RANGE")&&(s(t)?z(t[0],-D,-1,2,e)&&z(t[1],1,D,2,e)&&(k=0|t[0],q=0|t[1]):z(t,-D,D,2,e)&&(0|t?k=-(q=0|(0>t?-t:t)):$&&U(2,e+" cannot be zero",t))),r[e]=[k,q],f(e="ERRORS")&&(t===!!t||1===t||0===t?(L=0,z=($=!!t)?A:u):$&&U(2,e+y,t)),r[e]=$,f(e="CRYPTO")&&(t===!!t||1===t||0===t?(V=!(!t||!g||"object"!=typeof g),t&&!V&&$&&U(2,"crypto unavailable",g)):$&&U(2,e+y,t)),r[e]=V,f(e="MODULO_MODE")&&z(t,0,9,2,e)&&(W=0|t),r[e]=W,f(e="POW_PRECISION")&&z(t,0,D,2,e)&&(Y=0|t),r[e]=Y,f(e="FORMAT")&&("object"==typeof t?Z=t:$&&U(2,e+" not an object",t)),r[e]=Z,r},e.max=function(){return S(arguments,M.lt)},e.min=function(){return S(arguments,M.gt)},e.random=function(){var t=9007199254740992,n=Math.random()*t&2097151?function(){return w(Math.random()*t)}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)};return function(t){var r,i,o,f,u,s=0,c=[],a=new e(P);if(t=null!=t&&z(t,0,D,14)?0|t:B,f=v(t/I),V)if(g&&g.getRandomValues){for(r=g.getRandomValues(new Uint32Array(f*=2));f>s;)u=131072*r[s]+(r[s+1]>>>11),u>=9e15?(i=g.getRandomValues(new Uint32Array(2)),r[s]=i[0],r[s+1]=i[1]):(c.push(u%1e14),s+=2);s=f/2}else if(g&&g.randomBytes){for(r=g.randomBytes(f*=7);f>s;)u=281474976710656*(31&r[s])+1099511627776*r[s+1]+4294967296*r[s+2]+16777216*r[s+3]+(r[s+4]<<16)+(r[s+5]<<8)+r[s+6],u>=9e15?g.randomBytes(7).copy(r,s):(c.push(u%1e14),s+=7);s=f/7}else $&&U(14,"crypto unavailable",g);if(!s)for(;f>s;)u=n(),9e15>u&&(c[s++]=u%1e14);for(f=c[--s],t%=I,f&&t&&(u=_[I-t],c[s]=w(f/u)*u);0===c[s];c.pop(),s--);if(0>s)c=[o=0];else{for(o=-1;0===c[0];c.shift(),o-=I);for(s=1,u=c[0];u>=10;u/=10,s++);I>s&&(o-=I-s)}return a.e=o,a.c=c,a}}(),G=function(){function t(t,e,n){var r,i,o,f,u=0,s=t.length,c=e%T,a=e/T|0;for(t=t.slice();s--;)o=t[s]%T,f=t[s]/T|0,r=a*o+f*c,i=c*o+r%T*T+u,u=(i/n|0)+(r/T|0)+a*f,t[s]=i%n;return u&&t.unshift(u),t}function n(t,e,n,r){var i,o;if(n!=r)o=n>r?1:-1;else for(i=o=0;n>i;i++)if(t[i]!=e[i]){o=t[i]>e[i]?1:-1;break}return o}function r(t,e,n,r){for(var i=0;n--;)t[n]-=i,i=t[n]1;t.shift());}return function(o,f,u,s,c){var a,l,p,h,g,m,d,v,y,b,O,N,x,_,T,D,S,A=o.s==f.s?1:-1,R=o.c,U=f.c;if(!(R&&R[0]&&U&&U[0]))return new e(o.s&&f.s&&(R?!U||R[0]!=U[0]:U)?R&&0==R[0]||!U?0*A:A/0:0/0);for(v=new e(A),y=v.c=[],l=o.e-f.e,A=u+l+1,c||(c=E,l=i(o.e/I)-i(f.e/I),A=A/I|0),p=0;U[p]==(R[p]||0);p++);if(U[p]>(R[p]||0)&&l--,0>A)y.push(1),h=!0;else{for(_=R.length,D=U.length,p=0,A+=2,g=w(c/(U[0]+1)),g>1&&(U=t(U,g,c),R=t(R,g,c),D=U.length,_=R.length),x=D,b=R.slice(0,D),O=b.length;D>O;b[O++]=0);S=U.slice(),S.unshift(0),T=U[0],U[1]>=c/2&&T++;do g=0,a=n(U,b,D,O),0>a?(N=b[0],D!=O&&(N=N*c+(b[1]||0)),g=w(N/T),g>1?(g>=c&&(g=c-1),m=t(U,g,c),d=m.length,O=b.length,a=n(m,b,d,O),1==a&&(g--,r(m,d>D?S:U,d,c))):(0==g&&(a=g=1),m=U.slice()),d=m.length,O>d&&m.unshift(0),r(b,m,O,c),-1==a&&(O=b.length,a=n(U,b,D,O),1>a&&(g++,r(b,O>D?S:U,O,c))),O=b.length):0===a&&(g++,b=[0]),y[p++]=g,a&&b[0]?b[O++]=R[x]||0:(b=[R[x]],O=1);while((x++<_||null!=b[0])&&A--);h=null!=b[0],y[0]||y.shift()}if(c==E){for(p=1,A=y[0];A>=10;A/=10,p++);F(v,u+(v.e=p+l*I-1)+1,s,h)}else v.e=l,v.r=+h;return v}}(),m==function(){var t=/^(-?)0([xbo])(\w[\w.]*$)/i,n=/^([^.]+)\.$/,r=/^\.([^.]+)$/,i=/^-?(Infinity|NaN)$/,o=/^\s*\+([\w.])|^\s+|\s+$/g;return function(f,u,s,c){var a,l=s?u:u.replace(o,"$1");if(i.test(l))f.s=isNaN(l)?null:0>l?-1:1;else{if(!s&&(l=l.replace(t,function(t,e,n){return a="x"==(n=n.toLowerCase())?16:"b"==n?2:8,c&&c!=a?t:e}),c&&(a=c,l=l.replace(n,"$1").replace(r,"0.$1")),u!=l))return new e(l,a);$&&U(L,"not a"+(c?" base "+c:"")+" number",u),f.s=null}f.c=f.e=null,L=0}}(),M.absoluteValue=M.abs=function(){var t=new e(this);return t.s<0&&(t.s=1),t},M.ceil=function(){return F(new e(this),this.e+1,2)},M.comparedTo=M.cmp=function(t,n){return L=1,f(this,new e(t,n))},M.decimalPlaces=M.dp=function(){var t,e,n=this.c;if(!n)return null;if(t=((e=n.length-1)-i(this.e/I))*I,e=n[e])for(;e%10==0;e/=10,t--);return 0>t&&(t=0),t},M.dividedBy=M.div=function(t,n){return L=3,G(this,new e(t,n),B,H)},M.dividedToIntegerBy=M.divToInt=function(t,n){return L=4,G(this,new e(t,n),0,1)},M.equals=M.eq=function(t,n){return L=5,0===f(this,new e(t,n))},M.floor=function(){return F(new e(this),this.e+1,3)},M.greaterThan=M.gt=function(t,n){return L=6,f(this,new e(t,n))>0},M.greaterThanOrEqualTo=M.gte=function(t,n){return L=7,1===(n=f(this,new e(t,n)))||0===n},M.isFinite=function(){return!!this.c},M.isInteger=M.isInt=function(){return!!this.c&&i(this.e/I)>this.c.length-2},M.isNaN=function(){return!this.s},M.isNegative=M.isNeg=function(){return this.s<0},M.isZero=function(){return!!this.c&&0==this.c[0]},M.lessThan=M.lt=function(t,n){return L=8,f(this,new e(t,n))<0},M.lessThanOrEqualTo=M.lte=function(t,n){return L=9,-1===(n=f(this,new e(t,n)))||0===n},M.minus=M.sub=function(t,n){var r,o,f,u,s=this,c=s.s;if(L=10,t=new e(t,n),n=t.s,!c||!n)return new e(0/0);if(c!=n)return t.s=-n,s.plus(t);var a=s.e/I,l=t.e/I,p=s.c,h=t.c;if(!a||!l){if(!p||!h)return p?(t.s=-n,t):new e(h?s:0/0);if(!p[0]||!h[0])return h[0]?(t.s=-n,t):new e(p[0]?s:3==H?-0:0)}if(a=i(a),l=i(l),p=p.slice(),c=a-l){for((u=0>c)?(c=-c,f=p):(l=a,f=h),f.reverse(),n=c;n--;f.push(0));f.reverse()}else for(o=(u=(c=p.length)<(n=h.length))?c:n,c=n=0;o>n;n++)if(p[n]!=h[n]){u=p[n]0)for(;n--;p[r++]=0);for(n=E-1;o>c;){if(p[--o]0?(s=u,r=a):(f=-f,r=c),r.reverse();f--;r.push(0));r.reverse()}for(f=c.length,n=a.length,0>f-n&&(r=a,a=c,c=r,n=f),f=0;n;)f=(c[--n]=c[n]+a[n]+f)/E|0,c[n]%=E;return f&&(c.unshift(f),++s),R(t,c,s)},M.precision=M.sd=function(t){var e,n,r=this,i=r.c;if(null!=t&&t!==!!t&&1!==t&&0!==t&&($&&U(13,"argument"+y,t),t!=!!t&&(t=null)),!i)return null;if(n=i.length-1,e=n*I+1,n=i[n]){for(;n%10==0;n/=10,e--);for(n=i[0];n>=10;n/=10,e++);}return t&&r.e+1>e&&(e=r.e+1),e},M.round=function(t,n){var r=new e(this);return(null==t||z(t,0,D,15))&&F(r,~~t+this.e+1,null!=n&&z(n,0,8,15,b)?0|n:H),r},M.shift=function(t){var n=this;return z(t,-x,x,16,"argument")?n.times("1e"+p(t)):new e(n.c&&n.c[0]&&(-x>t||t>x)?n.s*(0>t?0:1/0):n)},M.squareRoot=M.sqrt=function(){var t,n,r,f,u,s=this,c=s.c,a=s.s,l=s.e,p=B+4,h=new e("0.5");if(1!==a||!c||!c[0])return new e(!a||0>a&&(!c||c[0])?0/0:c?s:1/0);if(a=Math.sqrt(+s),0==a||a==1/0?(n=o(c),(n.length+l)%2==0&&(n+="0"),a=Math.sqrt(n),l=i((l+1)/2)-(0>l||l%2),a==1/0?n="1e"+l:(n=a.toExponential(),n=n.slice(0,n.indexOf("e")+1)+l),r=new e(n)):r=new e(a+""),r.c[0])for(l=r.e,a=l+p,3>a&&(a=0);;)if(u=r,r=h.times(u.plus(G(s,u,p,1))),o(u.c).slice(0,a)===(n=o(r.c)).slice(0,a)){if(r.ea&&(d=b,b=O,O=d,f=a,a=h,h=f),f=a+h,d=[];f--;d.push(0));for(v=E,w=T,f=h;--f>=0;){for(r=0,g=O[f]%w,m=O[f]/w|0,s=a,u=f+s;u>f;)l=b[--s]%w,p=b[s]/w|0,c=m*l+p*g,l=g*l+c%w*w+d[u]+r,r=(l/v|0)+(c/w|0)+m*p,d[u--]=l%v;d[u]=r}return r?++o:d.shift(),R(t,d,o)},M.toDigits=function(t,n){var r=new e(this);return t=null!=t&&z(t,1,D,18,"precision")?0|t:null,n=null!=n&&z(n,0,8,18,b)?0|n:H,t?F(r,t,n):r},M.toExponential=function(t,e){return h(this,null!=t&&z(t,0,D,19)?~~t+1:null,e,19)},M.toFixed=function(t,e){return h(this,null!=t&&z(t,0,D,20)?~~t+this.e+1:null,e,20)},M.toFormat=function(t,e){var n=h(this,null!=t&&z(t,0,D,21)?~~t+this.e+1:null,e,21);if(this.c){var r,i=n.split("."),o=+Z.groupSize,f=+Z.secondaryGroupSize,u=Z.groupSeparator,s=i[0],c=i[1],a=this.s<0,l=a?s.slice(1):s,p=l.length;if(f&&(r=o,o=f,f=r,p-=r),o>0&&p>0){for(r=p%o||o,s=l.substr(0,r);p>r;r+=o)s+=u+l.substr(r,o);f>0&&(s+=u+l.slice(r)),a&&(s="-"+s)}n=c?s+Z.decimalSeparator+((f=+Z.fractionGroupSize)?c.replace(new RegExp("\\d{"+f+"}\\B","g"),"$&"+Z.fractionGroupSeparator):c):s}return n},M.toFraction=function(t){var n,r,i,f,u,s,c,a,l,p=$,h=this,g=h.c,m=new e(P),d=r=new e(P),v=c=new e(P);if(null!=t&&($=!1,s=new e(t),$=p,(!(p=s.isInt())||s.lt(P))&&($&&U(22,"max denominator "+(p?"out of range":"not an integer"),t),t=!p&&s.c&&F(s,s.e+1,1).gte(P)?s:null)),!g)return h.toString();for(l=o(g),f=m.e=l.length-h.e-1,m.c[0]=_[(u=f%I)<0?I+u:u],t=!t||s.cmp(m)>0?f>0?m:d:s,u=q,q=1/0,s=new e(l),c.c[0]=0;a=G(s,m,0,1),i=r.plus(a.times(v)),1!=i.cmp(t);)r=v,v=i,d=c.plus(a.times(i=d)),c=i,m=s.minus(a.times(i=m)),s=i;return i=G(t.minus(r),v,0,1),c=c.plus(i.times(d)),r=r.plus(i.times(v)),c.s=d.s=h.s,f*=2,n=G(d,v,f,H).minus(h).abs().cmp(G(c,r,f,H).minus(h).abs())<1?[d.toString(),v.toString()]:[c.toString(),r.toString()],q=u,n},M.toNumber=function(){var t=this;return+t||(t.s?0*t.s:0/0)},M.toPower=M.pow=function(t){var n,r,i=w(0>t?-t:+t),o=this;if(!z(t,-x,x,23,"exponent")&&(!isFinite(t)||i>x&&(t/=0)||parseFloat(t)!=t&&!(t=0/0)))return new e(Math.pow(+o,t));for(n=Y?v(Y/I+2):0,r=new e(P);;){if(i%2){if(r=r.times(o),!r.c)break;n&&r.c.length>n&&(r.c.length=n)}if(i=w(i/2),!i)break;o=o.times(o),n&&o.c&&o.c.length>n&&(o.c.length=n)}return 0>t&&(r=P.div(r)),n?F(r,Y,H):r},M.toPrecision=function(t,e){return h(this,null!=t&&z(t,1,D,24,"precision")?0|t:null,e,24)},M.toString=function(t){var e,r=this,i=r.s,f=r.e;return null===f?i?(e="Infinity",0>i&&(e="-"+e)):e="NaN":(e=o(r.c),e=null!=t&&z(t,2,64,25,"base")?n(l(e,f),0|t,10,i):C>=f||f>=j?a(e,f):l(e,f),0>i&&r.c[0]&&(e="-"+e)),e},M.truncated=M.trunc=function(){return F(new e(this),this.e+1,1)},M.valueOf=M.toJSON=function(){return this.toString()},null!=t&&e.config(t),e}function i(t){var e=0|t;return t>0||t===e?e:e-1}function o(t){for(var e,n,r=1,i=t.length,o=t[0]+"";i>r;){for(e=t[r++]+"",n=I-e.length;n--;e="0"+e);o+=e}for(i=o.length;48===o.charCodeAt(--i););return o.slice(0,i+1||1)}function f(t,e){var n,r,i=t.c,o=e.c,f=t.s,u=e.s,s=t.e,c=e.e;if(!f||!u)return null;if(n=i&&!i[0],r=o&&!o[0],n||r)return n?r?0:-u:f;if(f!=u)return f;if(n=0>f,r=s==c,!i||!o)return r?0:!i^n?1:-1;if(!r)return s>c^n?1:-1;for(u=(s=i.length)<(c=o.length)?s:c,f=0;u>f;f++)if(i[f]!=o[f])return i[f]>o[f]^n?1:-1;return s==c?0:s>c^n?1:-1}function u(t,e,n){return(t=p(t))>=e&&n>=t}function s(t){return"[object Array]"==Object.prototype.toString.call(t)}function c(t,e,n){for(var r,i,o=[0],f=0,u=t.length;u>f;){for(i=o.length;i--;o[i]*=e);for(o[r=0]+=N.indexOf(t.charAt(f++));rn-1&&(null==o[r+1]&&(o[r+1]=0),o[r+1]+=o[r]/n|0,o[r]%=n)}return o.reverse()}function a(t,e){return(t.length>1?t.charAt(0)+"."+t.slice(1):t)+(0>e?"e":"e+")+e}function l(t,e){var n,r;if(0>e){for(r="0.";++e;r+="0");t=r+t}else if(n=t.length,++e>n){for(r="0",e-=n;--e;r+="0");t+=r}else n>e&&(t=t.slice(0,e)+"."+t.slice(e));return t}function p(t){return t=parseFloat(t),0>t?v(t):w(t)}var h,g,m,d=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,v=Math.ceil,w=Math.floor,y=" not a boolean or binary digit",b="rounding mode",O="number type has more than 15 significant digits",N="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_",E=1e14,I=14,x=9007199254740991,_=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],T=1e7,D=1e9;if(h=r(),"function"==typeof define&&define.amd)define(function(){return h});else if("undefined"!=typeof e&&e.exports){if(e.exports=h,!g)try{g=t("crypto")}catch(S){}}else n.BigNumber=h}(this)},{crypto:1}],natspec:[function(t,e){var n=t("./node_modules/ethereum.js/lib/abi.js"),r=function(){var t=function(t,e){Object.keys(t).forEach(function(n){e[n]=t[n]})},e=function(t){return Object.keys(t).reduce(function(t,e){return t+"var "+e+" = context['"+e+"'];\n"},"")},r=function(t,e){return t.filter(function(t){return t.name===e})[0]},i=function(t,e){var r=n.formatOutput(t.inputs,"0x"+e.params[0].data.slice(10));return t.inputs.reduce(function(t,e,n){return t[e.name]=r[n],t},{})},o=function(t,e){var n,r="",i=/\` + "`" + `(?:\\.|[^` + "`" + `\\])*\` + "`" + `/gim,o=0;try{for(;null!==(n=i.exec(t));){var f=i.lastIndex-n[0].length,u=n[0].slice(1,n[0].length-1);r+=t.slice(o,f);var s=e(u);r+=s,o=i.lastIndex}r+=t.slice(o)}catch(c){throw new Error("Natspec evaluation failed, wrong input params")}return r},f=function(n,f){var u={};if(f)try{var s=r(f.abi,f.method),c=i(s,f.transaction);t(c,u)}catch(a){throw new Error("Natspec evaluation failed, method does not exist")}var l=e(u),p=o(n,function(t){var e=new Function("context",l+"return "+t+";");return e(u).toString()});return p},u=function(t,e){try{return f(t,e)}catch(n){return n.message}};return{evaluateExpression:f,evaluateExpressionSafe:u}}();e.exports=r},{"./node_modules/ethereum.js/lib/abi.js":3}]},{},[]); -//# sourceMappingURL=natspec.js.map` diff --git a/ethutil/natspec/natspec_test.go b/ethutil/natspec/natspec_test.go deleted file mode 100644 index 330dc831d..000000000 --- a/ethutil/natspec/natspec_test.go +++ /dev/null @@ -1,97 +0,0 @@ -package natspec - -import ( - "testing" -) - -func TestNotice(t *testing.T) { - - tx := ` - { - "jsonrpc": "2.0", - "method": "eth_call", - "params": [{ - "to": "0x8521742d3f456bd237e312d6e30724960f72517a", - "data": "0xc6888fa1000000000000000000000000000000000000000000000000000000000000007a" - }], - "id": 6 - } - ` - - abi := ` - [{ - "name": "multiply", - "constant": false, - "type": "function", - "inputs": [{ - "name": "a", - "type": "uint256" - }], - "outputs": [{ - "name": "d", - "type": "uint256" - }] - }] - ` - - desc := "Will multiply `a` by 7 and return `a * 7`." - - method := "multiply" - - ns, err := New() - if err != nil { - t.Errorf("NewNATSpec error %v", err) - } - - notice, err := ns.Notice(tx, abi, method, desc) - - if err != nil { - t.Errorf("expected no error got %v", err) - } - - expected := "Will multiply 122 by 7 and return 854." - if notice != expected { - t.Errorf("incorrect notice. expected %v, got %v", expected, notice) - } else { - t.Logf("returned notice \"%v\"", notice) - } - - notice, err = ns.Notice(tx, abi, method, "Will multiply 122 by \"7\" and return 854.") - - expected = "natspec.js error setting expression: (anonymous): Line 1:41 Unexpected number" - - if err == nil { - t.Errorf("expected error, got nothing (notice: '%v')", err, notice) - } else { - if err.Error() != expected { - t.Errorf("expected error '%s' got '%v' (notice: '%v')", expected, err, notice) - } - } - - // https://github.com/ethereum/natspec.js/issues/1 - badDesc := "Will multiply `e` by 7 and return `a * 7`." - notice, err = ns.Notice(tx, abi, method, badDesc) - - expected = "natspec.js error evaluating expression: Error: Natspec evaluation failed, wrong input params" - - if err == nil { - t.Errorf("expected error, got nothing (notice: '%v')", notice) - } else { - if err.Error() != expected { - t.Errorf("expected error '%s' got '%v' (notice: '%v')", expected, err, notice) - } - } - - notice, err = ns.Notice(tx, abi, "missing_method", desc) - - expected = "natspec.js error evaluating expression: Error: Natspec evaluation failed, method does not exist" - - if err == nil { - t.Errorf("expected error, got nothing (notice: '%v')", notice) - } else { - if err.Error() != expected { - t.Errorf("expected error '%s' got '%v' (notice: '%v')", expected, err, notice) - } - } - -} diff --git a/ethutil/number/int.go b/ethutil/number/int.go deleted file mode 100644 index 9a41fe3e5..000000000 --- a/ethutil/number/int.go +++ /dev/null @@ -1,181 +0,0 @@ -package number - -import ( - "math/big" - - "github.com/ethereum/go-ethereum/ethutil" -) - -var tt256 = new(big.Int).Lsh(big.NewInt(1), 256) -var tt256m1 = new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), 256), big.NewInt(1)) -var tt255 = new(big.Int).Lsh(big.NewInt(1), 255) - -func limitUnsigned256(x *Number) *Number { - x.num.And(x.num, tt256m1) - return x -} - -func limitSigned256(x *Number) *Number { - if x.num.Cmp(tt255) < 0 { - return x - } else { - x.num.Sub(x.num, tt256) - return x - } -} - -// Number function -type Initialiser func(n int64) *Number - -// A Number represents a generic integer with a bounding function limiter. Limit is called after each operations -// to give "fake" bounded integers. New types of Number can be created through NewInitialiser returning a lambda -// with the new Initialiser. -type Number struct { - num *big.Int - limit func(n *Number) *Number -} - -// Returns a new initialiser for a new *Number without having to expose certain fields -func NewInitialiser(limiter func(*Number) *Number) Initialiser { - return func(n int64) *Number { - return &Number{big.NewInt(n), limiter} - } -} - -// Return a Number with a UNSIGNED limiter up to 256 bits -func Uint256(n int64) *Number { - return &Number{big.NewInt(n), limitUnsigned256} -} - -// Return a Number with a SIGNED limiter up to 256 bits -func Int256(n int64) *Number { - return &Number{big.NewInt(n), limitSigned256} -} - -// Returns a Number with a SIGNED unlimited size -func Big(n int64) *Number { - return &Number{big.NewInt(n), func(x *Number) *Number { return x }} -} - -// Sets i to sum of x+y -func (i *Number) Add(x, y *Number) *Number { - i.num.Add(x.num, y.num) - return i.limit(i) -} - -// Sets i to difference of x-y -func (i *Number) Sub(x, y *Number) *Number { - i.num.Sub(x.num, y.num) - return i.limit(i) -} - -// Sets i to product of x*y -func (i *Number) Mul(x, y *Number) *Number { - i.num.Mul(x.num, y.num) - return i.limit(i) -} - -// Sets i to the quotient prodject of x/y -func (i *Number) Div(x, y *Number) *Number { - i.num.Div(x.num, y.num) - return i.limit(i) -} - -// Sets i to x % y -func (i *Number) Mod(x, y *Number) *Number { - i.num.Mod(x.num, y.num) - return i.limit(i) -} - -// Sets i to x << s -func (i *Number) Lsh(x *Number, s uint) *Number { - i.num.Lsh(x.num, s) - return i.limit(i) -} - -// Sets i to x^y -func (i *Number) Pow(x, y *Number) *Number { - i.num.Exp(x.num, y.num, big.NewInt(0)) - return i.limit(i) -} - -// Setters - -// Set x to i -func (i *Number) Set(x *Number) *Number { - i.num.Set(x.num) - return i.limit(i) -} - -// Set x bytes to i -func (i *Number) SetBytes(x []byte) *Number { - i.num.SetBytes(x) - return i.limit(i) -} - -// Cmp compares x and y and returns: -// -// -1 if x < y -// 0 if x == y -// +1 if x > y -func (i *Number) Cmp(x *Number) int { - return i.num.Cmp(x.num) -} - -// Getters - -// Returns the string representation of i -func (i *Number) String() string { - return i.num.String() -} - -// Returns the byte representation of i -func (i *Number) Bytes() []byte { - return i.num.Bytes() -} - -// Uint64 returns the Uint64 representation of x. If x cannot be represented in an int64, the result is undefined. -func (i *Number) Uint64() uint64 { - return i.num.Uint64() -} - -// Int64 returns the int64 representation of x. If x cannot be represented in an int64, the result is undefined. -func (i *Number) Int64() int64 { - return i.num.Int64() -} - -// Returns the signed version of i -func (i *Number) Int256() *Number { - return Int(0).Set(i) -} - -// Returns the unsigned version of i -func (i *Number) Uint256() *Number { - return Uint(0).Set(i) -} - -// Returns the index of the first bit that's set to 1 -func (i *Number) FirstBitSet() int { - for j := 0; j < i.num.BitLen(); j++ { - if i.num.Bit(j) > 0 { - return j - } - } - - return i.num.BitLen() -} - -// Variables - -var ( - Zero = Uint(0) - One = Uint(1) - Two = Uint(2) - MaxUint256 = Uint(0).SetBytes(ethutil.Hex2Bytes("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - - MinOne = Int(-1) - - // "typedefs" - Uint = Uint256 - Int = Int256 -) diff --git a/ethutil/number/uint_test.go b/ethutil/number/uint_test.go deleted file mode 100644 index c42989465..000000000 --- a/ethutil/number/uint_test.go +++ /dev/null @@ -1,92 +0,0 @@ -package number - -import ( - "math/big" - "testing" - - "github.com/ethereum/go-ethereum/ethutil" -) - -func TestSet(t *testing.T) { - a := Uint(0) - b := Uint(10) - a.Set(b) - if a.num.Cmp(b.num) != 0 { - t.Error("didn't compare", a, b) - } - - c := Uint(0).SetBytes(ethutil.Hex2Bytes("0a")) - if c.num.Cmp(big.NewInt(10)) != 0 { - t.Error("c set bytes failed.") - } -} - -func TestInitialiser(t *testing.T) { - check := false - init := NewInitialiser(func(x *Number) *Number { - check = true - return x - }) - a := init(0).Add(init(1), init(2)) - if a.Cmp(init(3)) != 0 { - t.Error("expected 3. got", a) - } - if !check { - t.Error("expected limiter to be called") - } -} - -func TestGet(t *testing.T) { - a := Uint(10) - if a.Uint64() != 10 { - t.Error("expected to get 10. got", a.Uint64()) - } - - a = Uint(10) - if a.Int64() != 10 { - t.Error("expected to get 10. got", a.Int64()) - } -} - -func TestCmp(t *testing.T) { - a := Uint(10) - b := Uint(10) - c := Uint(11) - - if a.Cmp(b) != 0 { - t.Error("a b == 0 failed", a, b) - } - - if a.Cmp(c) >= 0 { - t.Error("a c < 0 failed", a, c) - } - - if c.Cmp(b) <= 0 { - t.Error("c b > 0 failed", c, b) - } -} - -func TestMaxArith(t *testing.T) { - a := Uint(0).Add(MaxUint256, One) - if a.Cmp(Zero) != 0 { - t.Error("expected max256 + 1 = 0 got", a) - } - - a = Uint(0).Sub(Uint(0), One) - if a.Cmp(MaxUint256) != 0 { - t.Error("expected 0 - 1 = max256 got", a) - } - - a = Int(0).Sub(Int(0), One) - if a.Cmp(MinOne) != 0 { - t.Error("expected 0 - 1 = -1 got", a) - } -} - -func TestConversion(t *testing.T) { - a := Int(-1) - b := a.Uint256() - if b.Cmp(MaxUint256) != 0 { - t.Error("expected -1 => unsigned to return max. got", b) - } -} diff --git a/ethutil/package.go b/ethutil/package.go deleted file mode 100644 index e5df989d2..000000000 --- a/ethutil/package.go +++ /dev/null @@ -1,123 +0,0 @@ -package ethutil - -import ( - "archive/zip" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "strings" -) - -// Manifest object -// -// The manifest object holds all the relevant information supplied with the -// the manifest specified in the package -type Manifest struct { - Entry string - Height, Width int -} - -// External package -// -// External package contains the main html file and manifest -type ExtPackage struct { - EntryHtml string - Manifest *Manifest -} - -// Read file -// -// Read a given compressed file and returns the read bytes. -// Returns an error otherwise -func ReadFile(f *zip.File) ([]byte, error) { - rc, err := f.Open() - if err != nil { - return nil, err - } - defer rc.Close() - - content, err := ioutil.ReadAll(rc) - if err != nil { - return nil, err - } - - return content, nil -} - -// Reads manifest -// -// Reads and returns a manifest object. Returns error otherwise -func ReadManifest(m []byte) (*Manifest, error) { - var manifest Manifest - - dec := json.NewDecoder(strings.NewReader(string(m))) - if err := dec.Decode(&manifest); err == io.EOF { - } else if err != nil { - return nil, err - } - - return &manifest, nil -} - -// Find file in archive -// -// Returns the index of the given file name if it exists. -1 if file not found -func FindFileInArchive(fn string, files []*zip.File) (index int) { - index = -1 - // Find the manifest first - for i, f := range files { - if f.Name == fn { - index = i - } - } - - return -} - -// Open package -// -// Opens a prepared ethereum package -// Reads the manifest file and determines file contents and returns and -// the external package. -func OpenPackage(fn string) (*ExtPackage, error) { - r, err := zip.OpenReader(fn) - if err != nil { - return nil, err - } - defer r.Close() - - manifestIndex := FindFileInArchive("manifest.json", r.File) - - if manifestIndex < 0 { - return nil, fmt.Errorf("No manifest file found in archive") - } - - f, err := ReadFile(r.File[manifestIndex]) - if err != nil { - return nil, err - } - - manifest, err := ReadManifest(f) - if err != nil { - return nil, err - } - - if manifest.Entry == "" { - return nil, fmt.Errorf("Entry file specified but appears to be empty: %s", manifest.Entry) - } - - entryIndex := FindFileInArchive(manifest.Entry, r.File) - if entryIndex < 0 { - return nil, fmt.Errorf("Entry file not found: '%s'", manifest.Entry) - } - - f, err = ReadFile(r.File[entryIndex]) - if err != nil { - return nil, err - } - - extPackage := &ExtPackage{string(f), manifest} - - return extPackage, nil -} diff --git a/ethutil/path.go b/ethutil/path.go deleted file mode 100644 index e545c8731..000000000 --- a/ethutil/path.go +++ /dev/null @@ -1,68 +0,0 @@ -package ethutil - -import ( - "io/ioutil" - "os" - "os/user" - "path" - "strings" -) - -func ExpandHomePath(p string) (path string) { - path = p - - // Check in case of paths like "/something/~/something/" - if len(path) > 1 && path[:2] == "~/" { - usr, _ := user.Current() - dir := usr.HomeDir - - path = strings.Replace(p, "~", dir, 1) - } - - return -} - -func FileExist(filePath string) bool { - _, err := os.Stat(filePath) - if err != nil && os.IsNotExist(err) { - return false - } - - return true -} - -func ReadAllFile(filePath string) (string, error) { - file, err := os.Open(filePath) - if err != nil { - return "", err - } - - data, err := ioutil.ReadAll(file) - if err != nil { - return "", err - } - - return string(data), nil -} - -func WriteFile(filePath string, content []byte) error { - fh, err := os.OpenFile(filePath, os.O_TRUNC|os.O_RDWR|os.O_CREATE, os.ModePerm) - if err != nil { - return err - } - defer fh.Close() - - _, err = fh.Write(content) - if err != nil { - return err - } - - return nil -} - -func AbsolutePath(Datadir string, filename string) string { - if path.IsAbs(filename) { - return filename - } - return path.Join(Datadir, filename) -} diff --git a/ethutil/path_test.go b/ethutil/path_test.go deleted file mode 100644 index 908c94ee7..000000000 --- a/ethutil/path_test.go +++ /dev/null @@ -1,51 +0,0 @@ -package ethutil - -import ( - // "os" - "testing" -) - -func TestGoodFile(t *testing.T) { - goodpath := "~/goethereumtest.pass" - path := ExpandHomePath(goodpath) - contentstring := "3.14159265358979323846" - - err := WriteFile(path, []byte(contentstring)) - if err != nil { - t.Error("Could not write file") - } - - if !FileExist(path) { - t.Error("File not found at", path) - } - - v, err := ReadAllFile(path) - if err != nil { - t.Error("Could not read file", path) - } - if v != contentstring { - t.Error("Expected", contentstring, "Got", v) - } - -} - -func TestBadFile(t *testing.T) { - badpath := "/this/path/should/not/exist/goethereumtest.fail" - path := ExpandHomePath(badpath) - contentstring := "3.14159265358979323846" - - err := WriteFile(path, []byte(contentstring)) - if err == nil { - t.Error("Wrote file, but should not be able to", path) - } - - if FileExist(path) { - t.Error("Found file, but should not be able to", path) - } - - v, err := ReadAllFile(path) - if err == nil { - t.Error("Read file, but should not be able to", v) - } - -} diff --git a/ethutil/rlp.go b/ethutil/rlp.go deleted file mode 100644 index 0cb0d611c..000000000 --- a/ethutil/rlp.go +++ /dev/null @@ -1,276 +0,0 @@ -package ethutil - -import ( - "bytes" - "fmt" - "math/big" - "reflect" -) - -type RlpEncode interface { - RlpEncode() []byte -} - -type RlpEncodeDecode interface { - RlpEncode - RlpValue() []interface{} -} - -type RlpEncodable interface { - RlpData() interface{} -} - -func Rlp(encoder RlpEncode) []byte { - return encoder.RlpEncode() -} - -type RlpEncoder struct { - rlpData []byte -} - -func NewRlpEncoder() *RlpEncoder { - encoder := &RlpEncoder{} - - return encoder -} -func (coder *RlpEncoder) EncodeData(rlpData interface{}) []byte { - return Encode(rlpData) -} - -const ( - RlpEmptyList = 0x80 - RlpEmptyStr = 0x40 -) - -const rlpEof = -1 - -func Char(c []byte) int { - if len(c) > 0 { - return int(c[0]) - } - - return rlpEof -} - -func DecodeWithReader(reader *bytes.Buffer) interface{} { - var slice []interface{} - - // Read the next byte - char := Char(reader.Next(1)) - switch { - case char <= 0x7f: - return char - - case char <= 0xb7: - return reader.Next(int(char - 0x80)) - - case char <= 0xbf: - length := ReadVarInt(reader.Next(int(char - 0xb7))) - - return reader.Next(int(length)) - - case char <= 0xf7: - length := int(char - 0xc0) - for i := 0; i < length; i++ { - obj := DecodeWithReader(reader) - slice = append(slice, obj) - } - - return slice - case char <= 0xff: - length := ReadVarInt(reader.Next(int(char - 0xf7))) - for i := uint64(0); i < length; i++ { - obj := DecodeWithReader(reader) - slice = append(slice, obj) - } - - return slice - default: - panic(fmt.Sprintf("byte not supported: %q", char)) - } - - return slice -} - -var ( - directRlp = big.NewInt(0x7f) - numberRlp = big.NewInt(0xb7) - zeroRlp = big.NewInt(0x0) -) - -func intlen(i int64) (length int) { - for i > 0 { - i = i >> 8 - length++ - } - return -} - -func Encode(object interface{}) []byte { - var buff bytes.Buffer - - if object != nil { - switch t := object.(type) { - case *Value: - buff.Write(Encode(t.Raw())) - case RlpEncodable: - buff.Write(Encode(t.RlpData())) - // Code dup :-/ - case int: - buff.Write(Encode(big.NewInt(int64(t)))) - case uint: - buff.Write(Encode(big.NewInt(int64(t)))) - case int8: - buff.Write(Encode(big.NewInt(int64(t)))) - case int16: - buff.Write(Encode(big.NewInt(int64(t)))) - case int32: - buff.Write(Encode(big.NewInt(int64(t)))) - case int64: - buff.Write(Encode(big.NewInt(t))) - case uint16: - buff.Write(Encode(big.NewInt(int64(t)))) - case uint32: - buff.Write(Encode(big.NewInt(int64(t)))) - case uint64: - buff.Write(Encode(big.NewInt(int64(t)))) - case byte: - buff.Write(Encode(big.NewInt(int64(t)))) - case *big.Int: - // Not sure how this is possible while we check for nil - if t == nil { - buff.WriteByte(0xc0) - } else { - buff.Write(Encode(t.Bytes())) - } - case Bytes: - buff.Write(Encode([]byte(t))) - case []byte: - if len(t) == 1 && t[0] <= 0x7f { - buff.Write(t) - } else if len(t) < 56 { - buff.WriteByte(byte(len(t) + 0x80)) - buff.Write(t) - } else { - b := big.NewInt(int64(len(t))) - buff.WriteByte(byte(len(b.Bytes()) + 0xb7)) - buff.Write(b.Bytes()) - buff.Write(t) - } - case string: - buff.Write(Encode([]byte(t))) - case []interface{}: - // Inline function for writing the slice header - WriteSliceHeader := func(length int) { - if length < 56 { - buff.WriteByte(byte(length + 0xc0)) - } else { - b := big.NewInt(int64(length)) - buff.WriteByte(byte(len(b.Bytes()) + 0xf7)) - buff.Write(b.Bytes()) - } - } - - var b bytes.Buffer - for _, val := range t { - b.Write(Encode(val)) - } - WriteSliceHeader(len(b.Bytes())) - buff.Write(b.Bytes()) - default: - // This is how it should have been from the start - // needs refactoring (@fjl) - v := reflect.ValueOf(t) - switch v.Kind() { - case reflect.Slice: - var b bytes.Buffer - for i := 0; i < v.Len(); i++ { - b.Write(Encode(v.Index(i).Interface())) - } - - blen := b.Len() - if blen < 56 { - buff.WriteByte(byte(blen) + 0xc0) - } else { - ilen := byte(intlen(int64(blen))) - buff.WriteByte(ilen + 0xf7) - t := make([]byte, ilen) - for i := byte(0); i < ilen; i++ { - t[ilen-i-1] = byte(blen >> (i * 8)) - } - buff.Write(t) - } - buff.ReadFrom(&b) - } - } - } else { - // Empty list for nil - buff.WriteByte(0xc0) - } - - return buff.Bytes() -} - -// TODO Use a bytes.Buffer instead of a raw byte slice. -// Cleaner code, and use draining instead of seeking the next bytes to read -func Decode(data []byte, pos uint64) (interface{}, uint64) { - var slice []interface{} - char := int(data[pos]) - switch { - case char <= 0x7f: - return data[pos], pos + 1 - - case char <= 0xb7: - b := uint64(data[pos]) - 0x80 - - return data[pos+1 : pos+1+b], pos + 1 + b - - case char <= 0xbf: - b := uint64(data[pos]) - 0xb7 - - b2 := ReadVarInt(data[pos+1 : pos+1+b]) - - return data[pos+1+b : pos+1+b+b2], pos + 1 + b + b2 - - case char <= 0xf7: - b := uint64(data[pos]) - 0xc0 - prevPos := pos - pos++ - for i := uint64(0); i < b; { - var obj interface{} - - // Get the next item in the data list and append it - obj, prevPos = Decode(data, pos) - slice = append(slice, obj) - - // Increment i by the amount bytes read in the previous - // read - i += (prevPos - pos) - pos = prevPos - } - return slice, pos - - case char <= 0xff: - l := uint64(data[pos]) - 0xf7 - b := ReadVarInt(data[pos+1 : pos+1+l]) - - pos = pos + l + 1 - - prevPos := b - for i := uint64(0); i < uint64(b); { - var obj interface{} - - obj, prevPos = Decode(data, pos) - slice = append(slice, obj) - - i += (prevPos - pos) - pos = prevPos - } - return slice, pos - - default: - panic(fmt.Sprintf("byte not supported: %q", char)) - } - - return slice, 0 -} diff --git a/ethutil/rlp_test.go b/ethutil/rlp_test.go deleted file mode 100644 index ff98d3269..000000000 --- a/ethutil/rlp_test.go +++ /dev/null @@ -1,156 +0,0 @@ -package ethutil - -import ( - "bytes" - "math/big" - "reflect" - "testing" -) - -func TestNonInterfaceSlice(t *testing.T) { - vala := []string{"value1", "value2", "value3"} - valb := []interface{}{"value1", "value2", "value3"} - resa := Encode(vala) - resb := Encode(valb) - if !bytes.Equal(resa, resb) { - t.Errorf("expected []string & []interface{} to be equal") - } -} - -func TestRlpValueEncoding(t *testing.T) { - val := EmptyValue() - val.AppendList().Append(1).Append(2).Append(3) - val.Append("4").AppendList().Append(5) - - res := val.Encode() - exp := Encode([]interface{}{[]interface{}{1, 2, 3}, "4", []interface{}{5}}) - if bytes.Compare(res, exp) != 0 { - t.Errorf("expected %q, got %q", res, exp) - } -} - -func TestValueSlice(t *testing.T) { - val := []interface{}{ - "value1", - "valeu2", - "value3", - } - - value := NewValue(val) - splitVal := value.SliceFrom(1) - - if splitVal.Len() != 2 { - t.Error("SliceFrom: Expected len", 2, "got", splitVal.Len()) - } - - splitVal = value.SliceTo(2) - if splitVal.Len() != 2 { - t.Error("SliceTo: Expected len", 2, "got", splitVal.Len()) - } - - splitVal = value.SliceFromTo(1, 3) - if splitVal.Len() != 2 { - t.Error("SliceFromTo: Expected len", 2, "got", splitVal.Len()) - } -} - -func TestLargeData(t *testing.T) { - data := make([]byte, 100000) - enc := Encode(data) - value := NewValue(enc) - value.Decode() - - if value.Len() != len(data) { - t.Error("Expected data to be", len(data), "got", value.Len()) - } -} - -func TestValue(t *testing.T) { - value := NewValueFromBytes([]byte("\xcd\x83dog\x83god\x83cat\x01")) - if value.Get(0).Str() != "dog" { - t.Errorf("expected '%v', got '%v'", value.Get(0).Str(), "dog") - } - - if value.Get(3).Uint() != 1 { - t.Errorf("expected '%v', got '%v'", value.Get(3).Uint(), 1) - } -} - -func TestEncode(t *testing.T) { - strRes := "\x83dog" - bytes := Encode("dog") - - str := string(bytes) - if str != strRes { - t.Errorf("Expected %q, got %q", strRes, str) - } - - sliceRes := "\xcc\x83dog\x83god\x83cat" - strs := []interface{}{"dog", "god", "cat"} - bytes = Encode(strs) - slice := string(bytes) - if slice != sliceRes { - t.Error("Expected %q, got %q", sliceRes, slice) - } - - intRes := "\x82\x04\x00" - bytes = Encode(1024) - if string(bytes) != intRes { - t.Errorf("Expected %q, got %q", intRes, bytes) - } -} - -func TestDecode(t *testing.T) { - single := []byte("\x01") - b, _ := Decode(single, 0) - - if b.(uint8) != 1 { - t.Errorf("Expected 1, got %q", b) - } - - str := []byte("\x83dog") - b, _ = Decode(str, 0) - if bytes.Compare(b.([]byte), []byte("dog")) != 0 { - t.Errorf("Expected dog, got %q", b) - } - - slice := []byte("\xcc\x83dog\x83god\x83cat") - res := []interface{}{"dog", "god", "cat"} - b, _ = Decode(slice, 0) - if reflect.DeepEqual(b, res) { - t.Errorf("Expected %q, got %q", res, b) - } -} - -func TestEncodeDecodeBigInt(t *testing.T) { - bigInt := big.NewInt(1391787038) - encoded := Encode(bigInt) - - value := NewValueFromBytes(encoded) - if value.BigInt().Cmp(bigInt) != 0 { - t.Errorf("Expected %v, got %v", bigInt, value.BigInt()) - } -} - -func TestEncodeDecodeBytes(t *testing.T) { - b := NewValue([]interface{}{[]byte{1, 2, 3, 4, 5}, byte(6)}) - val := NewValueFromBytes(b.Encode()) - if !b.Cmp(val) { - t.Errorf("Expected %v, got %v", val, b) - } -} - -func TestEncodeZero(t *testing.T) { - b := NewValue(0).Encode() - exp := []byte{0xc0} - if bytes.Compare(b, exp) == 0 { - t.Error("Expected", exp, "got", b) - } -} - -func BenchmarkEncodeDecode(b *testing.B) { - for i := 0; i < b.N; i++ { - bytes := Encode([]interface{}{"dog", "god", "cat"}) - Decode(bytes, 0) - } -} diff --git a/ethutil/size.go b/ethutil/size.go deleted file mode 100644 index b4426465e..000000000 --- a/ethutil/size.go +++ /dev/null @@ -1,15 +0,0 @@ -package ethutil - -import "fmt" - -type StorageSize float64 - -func (self StorageSize) String() string { - if self > 1000000 { - return fmt.Sprintf("%.2f mB", self/1000000) - } else if self > 1000 { - return fmt.Sprintf("%.2f kB", self/1000) - } else { - return fmt.Sprintf("%.2f B", self) - } -} diff --git a/ethutil/size_test.go b/ethutil/size_test.go deleted file mode 100644 index e0f28abc5..000000000 --- a/ethutil/size_test.go +++ /dev/null @@ -1,23 +0,0 @@ -package ethutil - -import ( - checker "gopkg.in/check.v1" -) - -type SizeSuite struct{} - -var _ = checker.Suite(&SizeSuite{}) - -func (s *SizeSuite) TestStorageSizeString(c *checker.C) { - data1 := 2381273 - data2 := 2192 - data3 := 12 - - exp1 := "2.38 mB" - exp2 := "2.19 kB" - exp3 := "12.00 B" - - c.Assert(StorageSize(data1).String(), checker.Equals, exp1) - c.Assert(StorageSize(data2).String(), checker.Equals, exp2) - c.Assert(StorageSize(data3).String(), checker.Equals, exp3) -} diff --git a/ethutil/value.go b/ethutil/value.go deleted file mode 100644 index 7d4a7d98c..000000000 --- a/ethutil/value.go +++ /dev/null @@ -1,401 +0,0 @@ -package ethutil - -import ( - "bytes" - "fmt" - "math/big" - "reflect" - "strconv" -) - -// Data values are returned by the rlp decoder. The data values represents -// one item within the rlp data structure. It's responsible for all the casting -// It always returns something valid -type Value struct { - Val interface{} - kind reflect.Value -} - -func (val *Value) String() string { - return fmt.Sprintf("%x", val.Val) -} - -func NewValue(val interface{}) *Value { - t := val - if v, ok := val.(*Value); ok { - t = v.Val - } - - return &Value{Val: t} -} - -func (val *Value) Type() reflect.Kind { - return reflect.TypeOf(val.Val).Kind() -} - -func (val *Value) IsNil() bool { - return val.Val == nil -} - -func (val *Value) Len() int { - //return val.kind.Len() - if data, ok := val.Val.([]interface{}); ok { - return len(data) - } - - return len(val.Bytes()) -} - -func (val *Value) Raw() interface{} { - return val.Val -} - -func (val *Value) Interface() interface{} { - return val.Val -} - -func (val *Value) Uint() uint64 { - if Val, ok := val.Val.(uint8); ok { - return uint64(Val) - } else if Val, ok := val.Val.(uint16); ok { - return uint64(Val) - } else if Val, ok := val.Val.(uint32); ok { - return uint64(Val) - } else if Val, ok := val.Val.(uint64); ok { - return Val - } else if Val, ok := val.Val.(float32); ok { - return uint64(Val) - } else if Val, ok := val.Val.(float64); ok { - return uint64(Val) - } else if Val, ok := val.Val.(int); ok { - return uint64(Val) - } else if Val, ok := val.Val.(uint); ok { - return uint64(Val) - } else if Val, ok := val.Val.([]byte); ok { - return new(big.Int).SetBytes(Val).Uint64() - } else if Val, ok := val.Val.(*big.Int); ok { - return Val.Uint64() - } - - return 0 -} - -func (val *Value) Int() int64 { - if Val, ok := val.Val.(int8); ok { - return int64(Val) - } else if Val, ok := val.Val.(int16); ok { - return int64(Val) - } else if Val, ok := val.Val.(int32); ok { - return int64(Val) - } else if Val, ok := val.Val.(int64); ok { - return Val - } else if Val, ok := val.Val.(int); ok { - return int64(Val) - } else if Val, ok := val.Val.(float32); ok { - return int64(Val) - } else if Val, ok := val.Val.(float64); ok { - return int64(Val) - } else if Val, ok := val.Val.([]byte); ok { - return new(big.Int).SetBytes(Val).Int64() - } else if Val, ok := val.Val.(*big.Int); ok { - return Val.Int64() - } else if Val, ok := val.Val.(string); ok { - n, _ := strconv.Atoi(Val) - return int64(n) - } - - return 0 -} - -func (val *Value) Byte() byte { - if Val, ok := val.Val.(byte); ok { - return Val - } - - return 0x0 -} - -func (val *Value) BigInt() *big.Int { - if a, ok := val.Val.([]byte); ok { - b := new(big.Int).SetBytes(a) - - return b - } else if a, ok := val.Val.(*big.Int); ok { - return a - } else if a, ok := val.Val.(string); ok { - return Big(a) - } else { - return big.NewInt(int64(val.Uint())) - } - - return big.NewInt(0) -} - -func (val *Value) Str() string { - if a, ok := val.Val.([]byte); ok { - return string(a) - } else if a, ok := val.Val.(string); ok { - return a - } else if a, ok := val.Val.(byte); ok { - return string(a) - } - - return "" -} - -func (val *Value) Bytes() []byte { - if a, ok := val.Val.([]byte); ok { - return a - } else if s, ok := val.Val.(byte); ok { - return []byte{s} - } else if s, ok := val.Val.(string); ok { - return []byte(s) - } else if s, ok := val.Val.(*big.Int); ok { - return s.Bytes() - } else { - return big.NewInt(val.Int()).Bytes() - } - - return []byte{} -} - -func (val *Value) Err() error { - if err, ok := val.Val.(error); ok { - return err - } - - return nil -} - -func (val *Value) Slice() []interface{} { - if d, ok := val.Val.([]interface{}); ok { - return d - } - - return []interface{}{} -} - -func (val *Value) SliceFrom(from int) *Value { - slice := val.Slice() - - return NewValue(slice[from:]) -} - -func (val *Value) SliceTo(to int) *Value { - slice := val.Slice() - - return NewValue(slice[:to]) -} - -func (val *Value) SliceFromTo(from, to int) *Value { - slice := val.Slice() - - return NewValue(slice[from:to]) -} - -// TODO More type checking methods -func (val *Value) IsSlice() bool { - return val.Type() == reflect.Slice -} - -func (val *Value) IsStr() bool { - return val.Type() == reflect.String -} - -func (self *Value) IsErr() bool { - _, ok := self.Val.(error) - return ok -} - -// Special list checking function. Something is considered -// a list if it's of type []interface{}. The list is usually -// used in conjunction with rlp decoded streams. -func (val *Value) IsList() bool { - _, ok := val.Val.([]interface{}) - - return ok -} - -func (val *Value) IsEmpty() bool { - return val.Val == nil || ((val.IsSlice() || val.IsStr()) && val.Len() == 0) -} - -// Threat the value as a slice -func (val *Value) Get(idx int) *Value { - if d, ok := val.Val.([]interface{}); ok { - // Guard for oob - if len(d) <= idx { - return NewValue(nil) - } - - if idx < 0 { - return NewValue(nil) - } - - return NewValue(d[idx]) - } - - // If this wasn't a slice you probably shouldn't be using this function - return NewValue(nil) -} - -func (self *Value) Copy() *Value { - switch val := self.Val.(type) { - case *big.Int: - return NewValue(new(big.Int).Set(val)) - case []byte: - return NewValue(CopyBytes(val)) - default: - return NewValue(self.Val) - } - - return nil -} - -func (val *Value) Cmp(o *Value) bool { - return reflect.DeepEqual(val.Val, o.Val) -} - -func (self *Value) DeepCmp(o *Value) bool { - return bytes.Compare(self.Bytes(), o.Bytes()) == 0 -} - -func (val *Value) Encode() []byte { - return Encode(val.Val) -} - -// Assume that the data we have is encoded -func (self *Value) Decode() { - v, _ := Decode(self.Bytes(), 0) - self.Val = v - //self.Val = DecodeWithReader(bytes.NewBuffer(self.Bytes())) -} - -func NewValueFromBytes(data []byte) *Value { - if len(data) != 0 { - value := NewValue(data) - value.Decode() - - return value - } - - return NewValue(nil) -} - -// Value setters -func NewSliceValue(s interface{}) *Value { - list := EmptyValue() - - if s != nil { - if slice, ok := s.([]interface{}); ok { - for _, val := range slice { - list.Append(val) - } - } else if slice, ok := s.([]string); ok { - for _, val := range slice { - list.Append(val) - } - } - } - - return list -} - -func EmptyValue() *Value { - return NewValue([]interface{}{}) -} - -func (val *Value) AppendList() *Value { - list := EmptyValue() - val.Val = append(val.Slice(), list) - - return list -} - -func (val *Value) Append(v interface{}) *Value { - val.Val = append(val.Slice(), v) - - return val -} - -const ( - valOpAdd = iota - valOpDiv - valOpMul - valOpPow - valOpSub -) - -// Math stuff -func (self *Value) doOp(op int, other interface{}) *Value { - left := self.BigInt() - right := NewValue(other).BigInt() - - switch op { - case valOpAdd: - self.Val = left.Add(left, right) - case valOpDiv: - self.Val = left.Div(left, right) - case valOpMul: - self.Val = left.Mul(left, right) - case valOpPow: - self.Val = left.Exp(left, right, Big0) - case valOpSub: - self.Val = left.Sub(left, right) - } - - return self -} - -func (self *Value) Add(other interface{}) *Value { - return self.doOp(valOpAdd, other) -} - -func (self *Value) Sub(other interface{}) *Value { - return self.doOp(valOpSub, other) -} - -func (self *Value) Div(other interface{}) *Value { - return self.doOp(valOpDiv, other) -} - -func (self *Value) Mul(other interface{}) *Value { - return self.doOp(valOpMul, other) -} - -func (self *Value) Pow(other interface{}) *Value { - return self.doOp(valOpPow, other) -} - -type ValueIterator struct { - value *Value - currentValue *Value - idx int -} - -func (val *Value) NewIterator() *ValueIterator { - return &ValueIterator{value: val} -} - -func (it *ValueIterator) Len() int { - return it.value.Len() -} - -func (it *ValueIterator) Next() bool { - if it.idx >= it.value.Len() { - return false - } - - it.currentValue = it.value.Get(it.idx) - it.idx++ - - return true -} - -func (it *ValueIterator) Value() *Value { - return it.currentValue -} - -func (it *ValueIterator) Idx() int { - return it.idx - 1 -} diff --git a/ethutil/value_test.go b/ethutil/value_test.go deleted file mode 100644 index 861d35184..000000000 --- a/ethutil/value_test.go +++ /dev/null @@ -1,70 +0,0 @@ -package ethutil - -import ( - "math/big" - - checker "gopkg.in/check.v1" -) - -type ValueSuite struct{} - -var _ = checker.Suite(&ValueSuite{}) - -func (s *ValueSuite) TestValueCmp(c *checker.C) { - val1 := NewValue("hello") - val2 := NewValue("world") - c.Assert(val1.Cmp(val2), checker.Equals, false) - - val3 := NewValue("hello") - val4 := NewValue("hello") - c.Assert(val3.Cmp(val4), checker.Equals, true) -} - -func (s *ValueSuite) TestValueTypes(c *checker.C) { - str := NewValue("str") - num := NewValue(1) - inter := NewValue([]interface{}{1}) - byt := NewValue([]byte{1, 2, 3, 4}) - bigInt := NewValue(big.NewInt(10)) - - strExp := "str" - numExp := uint64(1) - interExp := []interface{}{1} - bytExp := []byte{1, 2, 3, 4} - bigExp := big.NewInt(10) - - c.Assert(str.Str(), checker.Equals, strExp) - c.Assert(num.Uint(), checker.Equals, numExp) - c.Assert(NewValue(inter.Interface()).Cmp(NewValue(interExp)), checker.Equals, true) - c.Assert(byt.Bytes(), checker.DeepEquals, bytExp) - c.Assert(bigInt.BigInt(), checker.DeepEquals, bigExp) -} - -func (s *ValueSuite) TestIterator(c *checker.C) { - value := NewValue([]interface{}{1, 2, 3}) - iter := value.NewIterator() - values := []uint64{1, 2, 3} - i := 0 - for iter.Next() { - c.Assert(values[i], checker.Equals, iter.Value().Uint()) - i++ - } -} - -func (s *ValueSuite) TestMath(c *checker.C) { - data1 := NewValue(1) - data1.Add(1).Add(1) - exp1 := NewValue(3) - data2 := NewValue(2) - data2.Sub(1).Sub(1) - exp2 := NewValue(0) - - c.Assert(data1.DeepCmp(exp1), checker.Equals, true) - c.Assert(data2.DeepCmp(exp2), checker.Equals, true) -} - -func (s *ValueSuite) TestString(c *checker.C) { - data := "10" - exp := int64(10) - c.Assert(NewValue(data).Int(), checker.DeepEquals, exp) -} diff --git a/javascript/types.go b/javascript/types.go index 5f47c1735..a6a0bc8e2 100644 --- a/javascript/types.go +++ b/javascript/types.go @@ -2,7 +2,7 @@ package javascript import ( "fmt" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/state" "github.com/ethereum/go-ethereum/xeth" "github.com/obscuren/otto" @@ -18,7 +18,7 @@ func (self *JSStateObject) EachStorage(call otto.FunctionCall) otto.Value { it := self.Object.Trie().Iterator() for it.Next() { - cb.Call(self.eth.toVal(self), self.eth.toVal(ethutil.Bytes2Hex(it.Key)), self.eth.toVal(ethutil.Bytes2Hex(it.Value))) + cb.Call(self.eth.toVal(self), self.eth.toVal(common.Bytes2Hex(it.Key)), self.eth.toVal(common.Bytes2Hex(it.Value))) } return otto.UndefinedValue() @@ -44,10 +44,10 @@ type JSLog struct { func NewJSLog(log state.Log) JSLog { return JSLog{ - Address: ethutil.Bytes2Hex(log.Address()), - Topics: nil, //ethutil.Bytes2Hex(log.Address()), + Address: common.Bytes2Hex(log.Address()), + Topics: nil, //common.Bytes2Hex(log.Address()), Number: 0, - Data: ethutil.Bytes2Hex(log.Data()), + Data: common.Bytes2Hex(log.Data()), } } diff --git a/logger/log.go b/logger/log.go index baa3dfaf2..2dbec86de 100644 --- a/logger/log.go +++ b/logger/log.go @@ -6,11 +6,11 @@ import ( "log" "os" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" ) func openLogFile(datadir string, filename string) *os.File { - path := ethutil.AbsolutePath(datadir, filename) + path := common.AbsolutePath(datadir, filename) file, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) if err != nil { panic(fmt.Sprintf("error opening log file '%s': %v", filename, err)) diff --git a/miner/worker.go b/miner/worker.go index 5c4a13698..10fc6f508 100644 --- a/miner/worker.go +++ b/miner/worker.go @@ -9,7 +9,7 @@ import ( "github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/pow" @@ -155,10 +155,10 @@ func (self *worker) wait() { self.current.block.Header().MixDigest = work.MixDigest jsonlogger.LogJson(&logger.EthMinerNewBlock{ - BlockHash: ethutil.Bytes2Hex(block.Hash()), + BlockHash: common.Bytes2Hex(block.Hash()), BlockNumber: block.Number(), - ChainHeadHash: ethutil.Bytes2Hex(block.ParentHeaderHash), - BlockPrevHash: ethutil.Bytes2Hex(block.ParentHeaderHash), + ChainHeadHash: common.Bytes2Hex(block.ParentHeaderHash), + BlockPrevHash: common.Bytes2Hex(block.ParentHeaderHash), }) if err := self.chain.InsertChain(types.Blocks{self.current.block}); err == nil { @@ -221,7 +221,7 @@ gasLimit: self.current.state.AddBalance(self.coinbase, core.BlockReward) - self.current.state.Update(ethutil.Big0) + self.current.state.Update(common.Big0) self.push() } diff --git a/p2p/message.go b/p2p/message.go index f88c31d1d..14e4404c9 100644 --- a/p2p/message.go +++ b/p2p/message.go @@ -11,7 +11,7 @@ import ( "sync/atomic" "time" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/rlp" ) @@ -30,7 +30,7 @@ type Msg struct { // NewMsg creates an RLP-encoded message with the given code. func NewMsg(code uint64, params ...interface{}) Msg { - p := bytes.NewReader(ethutil.Encode(params)) + p := bytes.NewReader(common.Encode(params)) return Msg{Code: code, Size: uint32(p.Len()), Payload: p} } diff --git a/p2p/server.go b/p2p/server.go index 9762fcc6d..02f1b8572 100644 --- a/p2p/server.go +++ b/p2p/server.go @@ -9,7 +9,7 @@ import ( "sync" "time" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/p2p/discover" "github.com/ethereum/go-ethereum/p2p/nat" @@ -46,7 +46,7 @@ type Server struct { MaxPeers int // Name sets the node name of this server. - // Use ethutil.MakeName to create a name that follows existing conventions. + // Use common.MakeName to create a name that follows existing conventions. Name string // Bootstrap nodes are used to establish connectivity @@ -132,7 +132,7 @@ func (srv *Server) SuggestPeer(n *discover.Node) { func (srv *Server) Broadcast(protocol string, code uint64, data ...interface{}) { var payload []byte if data != nil { - payload = ethutil.Encode(data) + payload = common.Encode(data) } srv.lock.RLock() defer srv.lock.RUnlock() diff --git a/pow/dagger/dagger.go b/pow/dagger/dagger.go index 3da7683d5..f2d65e8ef 100644 --- a/pow/dagger/dagger.go +++ b/pow/dagger/dagger.go @@ -7,7 +7,7 @@ import ( "time" "github.com/ethereum/go-ethereum/crypto/sha3" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/logger" ) @@ -50,7 +50,7 @@ func (dag *Dagger) Search(hash, diff *big.Int) ([]byte, []byte, []byte) { dag.hash = hash - obj := ethutil.BigPow(2, 256) + obj := common.BigPow(2, 256) obj = obj.Div(obj, diff) Found = false @@ -75,7 +75,7 @@ func (dag *Dagger) Search(hash, diff *big.Int) ([]byte, []byte, []byte) { func (dag *Dagger) Verify(hash, diff, nonce *big.Int) bool { dag.hash = hash - obj := ethutil.BigPow(2, 256) + obj := common.BigPow(2, 256) obj = obj.Div(obj, diff) return dag.Eval(nonce).Cmp(obj) < 0 @@ -85,7 +85,7 @@ func DaggerVerify(hash, diff, nonce *big.Int) bool { dagger := &Dagger{} dagger.hash = hash - obj := ethutil.BigPow(2, 256) + obj := common.BigPow(2, 256) obj = obj.Div(obj, diff) return dagger.Eval(nonce).Cmp(obj) < 0 @@ -133,7 +133,7 @@ func Sum(sha hash.Hash) []byte { } func (dag *Dagger) Eval(N *big.Int) *big.Int { - pow := ethutil.BigPow(2, 26) + pow := common.BigPow(2, 26) dag.xn = pow.Div(N, pow) sha := sha3.NewKeccak256() diff --git a/pow/dagger/dagger_test.go b/pow/dagger/dagger_test.go index f3a71d1eb..f53f4bac9 100644 --- a/pow/dagger/dagger_test.go +++ b/pow/dagger/dagger_test.go @@ -4,12 +4,12 @@ import ( "math/big" "testing" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" ) func BenchmarkDaggerSearch(b *testing.B) { hash := big.NewInt(0) - diff := ethutil.BigPow(2, 36) + diff := common.BigPow(2, 36) o := big.NewInt(0) // nonce doesn't matter. We're only testing against speed, not validity // Reset timer so the big generation isn't included in the benchmark diff --git a/pow/ezp/pow.go b/pow/ezp/pow.go index 3ca502d06..7eba95784 100644 --- a/pow/ezp/pow.go +++ b/pow/ezp/pow.go @@ -7,7 +7,7 @@ import ( "time" "github.com/ethereum/go-ethereum/crypto/sha3" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/pow" ) @@ -91,8 +91,8 @@ func verify(hash []byte, diff *big.Int, nonce uint64) bool { d := append(hash, n...) sha.Write(d) - verification := new(big.Int).Div(ethutil.BigPow(2, 256), diff) - res := ethutil.BigD(sha.Sum(nil)) + verification := new(big.Int).Div(common.BigPow(2, 256), diff) + res := common.BigD(sha.Sum(nil)) return res.Cmp(verification) <= 0 } diff --git a/rpc/api.go b/rpc/api.go index 2137de356..1846e7db5 100644 --- a/rpc/api.go +++ b/rpc/api.go @@ -13,7 +13,7 @@ import ( "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/event/filter" "github.com/ethereum/go-ethereum/state" @@ -43,7 +43,7 @@ type EthereumApi struct { regmut sync.Mutex register map[string][]*NewTxArgs - db ethutil.Database + db common.Database } func NewEthereumApi(eth *xeth.XEth, dataDir string) *EthereumApi { @@ -241,7 +241,7 @@ func (p *EthereumApi) Transact(args *NewTxArgs, reply *interface{}) (err error) // p.register[args.From] = append(p.register[args.From], args) //} else { /* - account := accounts.Get(ethutil.FromHex(args.From)) + account := accounts.Get(common.FromHex(args.From)) if account != nil { if account.Unlocked() { if !unlockAccount(account) { @@ -249,7 +249,7 @@ func (p *EthereumApi) Transact(args *NewTxArgs, reply *interface{}) (err error) } } - result, _ := account.Transact(ethutil.FromHex(args.To), ethutil.FromHex(args.Value), ethutil.FromHex(args.Gas), ethutil.FromHex(args.GasPrice), ethutil.FromHex(args.Data)) + result, _ := account.Transact(common.FromHex(args.To), common.FromHex(args.Value), common.FromHex(args.Gas), common.FromHex(args.GasPrice), common.FromHex(args.Data)) if len(result) > 0 { *reply = toHex(result) } @@ -258,7 +258,7 @@ func (p *EthereumApi) Transact(args *NewTxArgs, reply *interface{}) (err error) } */ // TODO: align default values to have the same type, e.g. not depend on - // ethutil.Value conversions later on + // common.Value conversions later on if args.Gas.Cmp(big.NewInt(0)) == 0 { args.Gas = defaultGas } @@ -316,7 +316,7 @@ func (p *EthereumApi) GetStorageAt(args *GetStorageAtArgs, reply *interface{}) e } else { // Convert the incoming string (which is a bigint) into hex i, _ := new(big.Int).SetString(args.Key, 10) - hx = ethutil.Bytes2Hex(i.Bytes()) + hx = common.Bytes2Hex(i.Bytes()) } rpclogger.Debugf("GetStateAt(%s, %s)\n", args.Address, hx) *reply = map[string]string{args.Key: value.Str()} @@ -480,7 +480,7 @@ func (p *EthereumApi) GetRequestReply(req *RpcRequest, reply *interface{}) error if err := json.Unmarshal(req.Params, &args); err != nil { return err } - *reply = toHex(crypto.Sha3(ethutil.FromHex(args.Data))) + *reply = toHex(crypto.Sha3(common.FromHex(args.Data))) case "web3_clientVersion": *reply = p.xeth().Backend().Version() case "net_version": @@ -821,12 +821,12 @@ func toFilterOptions(options *FilterOptions) core.FilterOptions { // Convert optional address slice/string to byte slice if str, ok := options.Address.(string); ok { - opts.Address = [][]byte{ethutil.FromHex(str)} + opts.Address = [][]byte{common.FromHex(str)} } else if slice, ok := options.Address.([]interface{}); ok { bslice := make([][]byte, len(slice)) for i, addr := range slice { if saddr, ok := addr.(string); ok { - bslice[i] = ethutil.FromHex(saddr) + bslice[i] = common.FromHex(saddr) } } opts.Address = bslice @@ -840,11 +840,11 @@ func toFilterOptions(options *FilterOptions) core.FilterOptions { if slice, ok := topicDat.([]interface{}); ok { topics[i] = make([][]byte, len(slice)) for j, topic := range slice { - topics[i][j] = ethutil.FromHex(topic.(string)) + topics[i][j] = common.FromHex(topic.(string)) } } else if str, ok := topicDat.(string); ok { topics[i] = make([][]byte, 1) - topics[i][0] = ethutil.FromHex(str) + topics[i][0] = common.FromHex(str) } } opts.Topics = topics diff --git a/rpc/args.go b/rpc/args.go index b935c5007..7ed482c30 100644 --- a/rpc/args.go +++ b/rpc/args.go @@ -5,7 +5,7 @@ import ( "encoding/json" "math/big" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" ) func blockNumber(raw json.RawMessage, number *int64) (err error) { @@ -20,7 +20,7 @@ func blockNumber(raw json.RawMessage, number *int64) (err error) { case "pending": *number = 0 default: - *number = ethutil.String2Big(str).Int64() + *number = common.String2Big(str).Int64() } return nil } @@ -73,7 +73,7 @@ func (args *GetBlockByNumberArgs) UnmarshalJSON(b []byte) (err error) { if v, ok := obj[0].(float64); ok { args.BlockNumber = int64(v) } else { - args.BlockNumber = ethutil.Big(obj[0].(string)).Int64() + args.BlockNumber = common.Big(obj[0].(string)).Int64() } if len(obj) > 1 { @@ -102,9 +102,9 @@ func (args *NewTxArgs) UnmarshalJSON(b []byte) (err error) { args.From = obj.From args.To = obj.To - args.Value = ethutil.Big(obj.Value) - args.Gas = ethutil.Big(obj.Gas) - args.GasPrice = ethutil.Big(obj.GasPrice) + args.Value = common.Big(obj.Value) + args.Gas = common.Big(obj.Gas) + args.GasPrice = common.Big(obj.GasPrice) args.Data = obj.Data return nil @@ -208,7 +208,7 @@ func (args *GetBalanceArgs) UnmarshalJSON(b []byte) (err error) { if obj[1].(string) == "latest" { args.BlockNumber = -1 } else { - args.BlockNumber = ethutil.Big(obj[1].(string)).Int64() + args.BlockNumber = common.Big(obj[1].(string)).Int64() } } @@ -266,14 +266,14 @@ func (args *BlockNumIndexArgs) UnmarshalJSON(b []byte) (err error) { if !ok { return NewDecodeParamError("BlockNumber is not string") } - args.BlockNumber = ethutil.Big(arg0).Int64() + args.BlockNumber = common.Big(arg0).Int64() if len(obj) > 1 { arg1, ok := obj[1].(string) if !ok { return NewDecodeParamError("Index not a string") } - args.Index = ethutil.Big(arg1).Int64() + args.Index = common.Big(arg1).Int64() } return nil @@ -306,7 +306,7 @@ func (args *HashIndexArgs) UnmarshalJSON(b []byte) (err error) { if !ok { return NewDecodeParamError("Index not a string") } - args.Index = ethutil.Big(arg1).Int64() + args.Index = common.Big(arg1).Int64() } return nil @@ -357,10 +357,10 @@ func (args *Sha3Args) UnmarshalJSON(b []byte) (err error) { // if len(obj) < 1 { // return errArguments // } -// args.FromBlock = uint64(ethutil.Big(obj[0].FromBlock).Int64()) -// args.ToBlock = uint64(ethutil.Big(obj[0].ToBlock).Int64()) -// args.Limit = uint64(ethutil.Big(obj[0].Limit).Int64()) -// args.Offset = uint64(ethutil.Big(obj[0].Offset).Int64()) +// args.FromBlock = uint64(common.Big(obj[0].FromBlock).Int64()) +// args.ToBlock = uint64(common.Big(obj[0].ToBlock).Int64()) +// args.Limit = uint64(common.Big(obj[0].Limit).Int64()) +// args.Offset = uint64(common.Big(obj[0].Offset).Int64()) // args.Address = obj[0].Address // args.Topics = obj[0].Topics @@ -394,10 +394,10 @@ func (args *FilterOptions) UnmarshalJSON(b []byte) (err error) { return NewInsufficientParamsError(len(obj), 1) } - args.Earliest = int64(ethutil.Big(obj[0].FromBlock).Int64()) - args.Latest = int64(ethutil.Big(obj[0].ToBlock).Int64()) - args.Max = int(ethutil.Big(obj[0].Limit).Int64()) - args.Skip = int(ethutil.Big(obj[0].Offset).Int64()) + args.Earliest = int64(common.Big(obj[0].FromBlock).Int64()) + args.Latest = int64(common.Big(obj[0].ToBlock).Int64()) + args.Max = int(common.Big(obj[0].Limit).Int64()) + args.Skip = int(common.Big(obj[0].Offset).Int64()) args.Address = obj[0].Address args.Topics = obj[0].Topics @@ -474,8 +474,8 @@ func (args *WhisperMessageArgs) UnmarshalJSON(b []byte) (err error) { args.To = obj[0].To args.From = obj[0].From args.Topics = obj[0].Topics - args.Priority = uint32(ethutil.Big(obj[0].Priority).Int64()) - args.Ttl = uint32(ethutil.Big(obj[0].Ttl).Int64()) + args.Priority = uint32(common.Big(obj[0].Priority).Int64()) + args.Ttl = uint32(common.Big(obj[0].Ttl).Int64()) return nil } @@ -538,7 +538,7 @@ func (args *FilterIdArgs) UnmarshalJSON(b []byte) (err error) { return NewInsufficientParamsError(len(obj), 1) } - args.Id = int(ethutil.Big(obj[0]).Int64()) + args.Id = int(common.Big(obj[0]).Int64()) return nil } diff --git a/rpc/util.go b/rpc/util.go index 4acd90284..08f404c99 100644 --- a/rpc/util.go +++ b/rpc/util.go @@ -25,7 +25,7 @@ import ( "reflect" "time" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/state" "github.com/ethereum/go-ethereum/xeth" @@ -120,7 +120,7 @@ func (self JsonWrapper) ParseRequestBody(req *http.Request) (RpcRequest, error) } func toHex(b []byte) string { - hex := ethutil.Bytes2Hex(b) + hex := common.Bytes2Hex(b) // Prefer output of "0x0" instead of "0x" if len(hex) == 0 { hex = "0" diff --git a/state/dump.go b/state/dump.go index 2c611d76b..c5f556e1a 100644 --- a/state/dump.go +++ b/state/dump.go @@ -4,7 +4,7 @@ import ( "encoding/json" "fmt" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" ) type Account struct { @@ -22,7 +22,7 @@ type World struct { func (self *StateDB) RawDump() World { world := World{ - Root: ethutil.Bytes2Hex(self.trie.Root()), + Root: common.Bytes2Hex(self.trie.Root()), Accounts: make(map[string]Account), } @@ -30,14 +30,14 @@ func (self *StateDB) RawDump() World { for it.Next() { stateObject := NewStateObjectFromBytes(it.Key, it.Value, self.db) - account := Account{Balance: stateObject.balance.String(), Nonce: stateObject.nonce, Root: ethutil.Bytes2Hex(stateObject.Root()), CodeHash: ethutil.Bytes2Hex(stateObject.codeHash)} + account := Account{Balance: stateObject.balance.String(), Nonce: stateObject.nonce, Root: common.Bytes2Hex(stateObject.Root()), CodeHash: common.Bytes2Hex(stateObject.codeHash)} account.Storage = make(map[string]string) storageIt := stateObject.State.trie.Iterator() for storageIt.Next() { - account.Storage[ethutil.Bytes2Hex(storageIt.Key)] = ethutil.Bytes2Hex(storageIt.Value) + account.Storage[common.Bytes2Hex(storageIt.Key)] = common.Bytes2Hex(storageIt.Value) } - world.Accounts[ethutil.Bytes2Hex(it.Key)] = account + world.Accounts[common.Bytes2Hex(it.Key)] = account } return world } diff --git a/state/log.go b/state/log.go index d503bd1a0..a0859aaf2 100644 --- a/state/log.go +++ b/state/log.go @@ -3,11 +3,11 @@ package state import ( "fmt" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" ) type Log interface { - ethutil.RlpEncodable + common.RlpEncodable Address() []byte Topics() [][]byte @@ -43,7 +43,7 @@ func (self *StateLog) Number() uint64 { return self.number } -func NewLogFromValue(decoder *ethutil.Value) *StateLog { +func NewLogFromValue(decoder *common.Value) *StateLog { log := &StateLog{ address: decoder.Get(0).Bytes(), data: decoder.Get(2).Bytes(), @@ -58,7 +58,7 @@ func NewLogFromValue(decoder *ethutil.Value) *StateLog { } func (self *StateLog) RlpData() interface{} { - return []interface{}{self.address, ethutil.ByteSliceToInterface(self.topics), self.data} + return []interface{}{self.address, common.ByteSliceToInterface(self.topics), self.data} } func (self *StateLog) String() string { diff --git a/state/managed_state_test.go b/state/managed_state_test.go index f819d8ad3..4aad1e1e3 100644 --- a/state/managed_state_test.go +++ b/state/managed_state_test.go @@ -3,10 +3,10 @@ package state import ( "testing" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" ) -var addr = ethutil.Address([]byte("test")) +var addr = common.Address([]byte("test")) func create() (*ManagedState, *account) { ms := ManageState(&StateDB{stateObjects: make(map[string]*StateObject)}) diff --git a/state/state_object.go b/state/state_object.go index dccbe8dad..8be9e28fc 100644 --- a/state/state_object.go +++ b/state/state_object.go @@ -6,7 +6,7 @@ import ( "math/big" "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/trie" ) @@ -17,7 +17,7 @@ func (self Code) String() string { return string(self) //strings.Join(Disassemble(self), " ") } -type Storage map[string]*ethutil.Value +type Storage map[string]*common.Value func (self Storage) String() (str string) { for key, value := range self { @@ -39,7 +39,7 @@ func (self Storage) Copy() Storage { type StateObject struct { // State database for storing state changes - db ethutil.Database + db common.Database // The state object State *StateDB @@ -77,12 +77,12 @@ func (self *StateObject) Reset() { self.State.Reset() } -func NewStateObject(addr []byte, db ethutil.Database) *StateObject { +func NewStateObject(addr []byte, db common.Database) *StateObject { // This to ensure that it has 20 bytes (and not 0 bytes), thus left or right pad doesn't matter. - address := ethutil.Address(addr) + address := common.Address(addr) object := &StateObject{db: db, address: address, balance: new(big.Int), gasPool: new(big.Int), dirty: true} - object.State = New(nil, db) //New(trie.New(ethutil.Config.Db, "")) + object.State = New(nil, db) //New(trie.New(common.Config.Db, "")) object.storage = make(Storage) object.gasPool = new(big.Int) object.prepaid = new(big.Int) @@ -90,7 +90,7 @@ func NewStateObject(addr []byte, db ethutil.Database) *StateObject { return object } -func NewStateObjectFromBytes(address, data []byte, db ethutil.Database) *StateObject { +func NewStateObjectFromBytes(address, data []byte, db common.Database) *StateObject { // TODO clean me up var extobject struct { Nonce uint64 @@ -110,7 +110,7 @@ func NewStateObjectFromBytes(address, data []byte, db ethutil.Database) *StateOb object.balance = extobject.Balance object.codeHash = extobject.CodeHash object.State = New(extobject.Root, db) - object.storage = make(map[string]*ethutil.Value) + object.storage = make(map[string]*common.Value) object.gasPool = new(big.Int) object.prepaid = new(big.Int) object.code, _ = db.Get(extobject.CodeHash) @@ -124,18 +124,18 @@ func (self *StateObject) MarkForDeletion() { statelogger.Debugf("%x: #%d %v X\n", self.Address(), self.nonce, self.balance) } -func (c *StateObject) getAddr(addr []byte) *ethutil.Value { - return ethutil.NewValueFromBytes([]byte(c.State.trie.Get(addr))) +func (c *StateObject) getAddr(addr []byte) *common.Value { + return common.NewValueFromBytes([]byte(c.State.trie.Get(addr))) } func (c *StateObject) setAddr(addr []byte, value interface{}) { - c.State.trie.Update(addr, ethutil.Encode(value)) + c.State.trie.Update(addr, common.Encode(value)) } -func (self *StateObject) GetStorage(key *big.Int) *ethutil.Value { +func (self *StateObject) GetStorage(key *big.Int) *common.Value { return self.GetState(key.Bytes()) } -func (self *StateObject) SetStorage(key *big.Int, value *ethutil.Value) { +func (self *StateObject) SetStorage(key *big.Int, value *common.Value) { self.SetState(key.Bytes(), value) } @@ -143,8 +143,8 @@ func (self *StateObject) Storage() Storage { return self.storage } -func (self *StateObject) GetState(k []byte) *ethutil.Value { - key := ethutil.LeftPadBytes(k, 32) +func (self *StateObject) GetState(k []byte) *common.Value { + key := common.LeftPadBytes(k, 32) value := self.storage[string(key)] if value == nil { @@ -158,8 +158,8 @@ func (self *StateObject) GetState(k []byte) *ethutil.Value { return value } -func (self *StateObject) SetState(k []byte, value *ethutil.Value) { - key := ethutil.LeftPadBytes(k, 32) +func (self *StateObject) SetState(k []byte, value *common.Value) { + key := common.LeftPadBytes(k, 32) self.storage[string(key)] = value.Copy() self.dirty = true } @@ -176,12 +176,12 @@ func (self *StateObject) Sync() { self.storage = make(Storage) } -func (c *StateObject) GetInstr(pc *big.Int) *ethutil.Value { +func (c *StateObject) GetInstr(pc *big.Int) *common.Value { if int64(len(c.code)-1) < pc.Int64() { - return ethutil.NewValue(0) + return common.NewValue(0) } - return ethutil.NewValueFromBytes([]byte{c.code[pc.Int64()]}) + return common.NewValueFromBytes([]byte{c.code[pc.Int64()]}) } func (c *StateObject) AddBalance(amount *big.Int) { @@ -252,13 +252,13 @@ func (self *StateObject) RefundGas(gas, price *big.Int) { func (self *StateObject) Copy() *StateObject { stateObject := NewStateObject(self.Address(), self.db) stateObject.balance.Set(self.balance) - stateObject.codeHash = ethutil.CopyBytes(self.codeHash) + stateObject.codeHash = common.CopyBytes(self.codeHash) stateObject.nonce = self.nonce if self.State != nil { stateObject.State = self.State.Copy() } - stateObject.code = ethutil.CopyBytes(self.code) - stateObject.initCode = ethutil.CopyBytes(self.initCode) + stateObject.code = common.CopyBytes(self.code) + stateObject.initCode = common.CopyBytes(self.initCode) stateObject.storage = self.storage.Copy() stateObject.gasPool.Set(self.gasPool) stateObject.remove = self.remove @@ -330,19 +330,19 @@ func (self *StateObject) Nonce() uint64 { // State object encoding methods func (c *StateObject) RlpEncode() []byte { - return ethutil.Encode([]interface{}{c.nonce, c.balance, c.Root(), c.CodeHash()}) + return common.Encode([]interface{}{c.nonce, c.balance, c.Root(), c.CodeHash()}) } -func (c *StateObject) CodeHash() ethutil.Bytes { +func (c *StateObject) CodeHash() common.Bytes { return crypto.Sha3(c.code) } func (c *StateObject) RlpDecode(data []byte) { - decoder := ethutil.NewValueFromBytes(data) + decoder := common.NewValueFromBytes(data) c.nonce = decoder.Get(0).Uint() c.balance = decoder.Get(1).BigInt() - c.State = New(decoder.Get(2).Bytes(), c.db) //New(trie.New(ethutil.Config.Db, decoder.Get(2).Interface())) - c.storage = make(map[string]*ethutil.Value) + c.State = New(decoder.Get(2).Bytes(), c.db) //New(trie.New(common.Config.Db, decoder.Get(2).Interface())) + c.storage = make(map[string]*common.Value) c.gasPool = new(big.Int) c.codeHash = decoder.Get(3).Bytes() diff --git a/state/state_test.go b/state/state_test.go index 07e35f7e2..3ecc03ae0 100644 --- a/state/state_test.go +++ b/state/state_test.go @@ -6,7 +6,7 @@ import ( checker "gopkg.in/check.v1" "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" ) type StateSuite struct { @@ -63,9 +63,9 @@ func (s *StateSuite) SetUpTest(c *checker.C) { func (s *StateSuite) TestSnapshot(c *checker.C) { stateobjaddr := []byte("aa") - storageaddr := ethutil.Big("0") - data1 := ethutil.NewValue(42) - data2 := ethutil.NewValue(43) + storageaddr := common.Big("0") + data1 := common.NewValue(42) + data2 := common.NewValue(43) // get state object stateObject := s.state.GetOrNewStateObject(stateobjaddr) diff --git a/state/statedb.go b/state/statedb.go index a0dc7732f..80bbe2afd 100644 --- a/state/statedb.go +++ b/state/statedb.go @@ -4,7 +4,7 @@ import ( "bytes" "math/big" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/trie" ) @@ -17,7 +17,7 @@ var statelogger = logger.NewLogger("STATE") // * Contracts // * Accounts type StateDB struct { - db ethutil.Database + db common.Database trie *trie.SecureTrie stateObjects map[string]*StateObject @@ -28,8 +28,8 @@ type StateDB struct { } // Create a new state from a given trie -func New(root []byte, db ethutil.Database) *StateDB { - trie := trie.NewSecure(ethutil.CopyBytes(root), db) +func New(root []byte, db common.Database) *StateDB { + trie := trie.NewSecure(common.CopyBytes(root), db) return &StateDB{db: db, trie: trie, stateObjects: make(map[string]*StateObject), refund: make(map[string]*big.Int)} } @@ -59,7 +59,7 @@ func (self *StateDB) GetBalance(addr []byte) *big.Int { return stateObject.balance } - return ethutil.Big0 + return common.Big0 } func (self *StateDB) AddBalance(addr []byte, amount *big.Int) { @@ -113,7 +113,7 @@ func (self *StateDB) SetCode(addr, code []byte) { func (self *StateDB) SetState(addr, key []byte, value interface{}) { stateObject := self.GetStateObject(addr) if stateObject != nil { - stateObject.SetState(key, ethutil.NewValue(value)) + stateObject.SetState(key, common.NewValue(value)) } } @@ -161,7 +161,7 @@ func (self *StateDB) DeleteStateObject(stateObject *StateObject) { // Retrieve a state object given my the address. Nil if not found func (self *StateDB) GetStateObject(addr []byte) *StateObject { - addr = ethutil.Address(addr) + addr = common.Address(addr) stateObject := self.stateObjects[string(addr)] if stateObject != nil { @@ -195,7 +195,7 @@ func (self *StateDB) GetOrNewStateObject(addr []byte) *StateObject { // Create a state object whether it exist in the trie or not func (self *StateDB) NewStateObject(addr []byte) *StateObject { - addr = ethutil.Address(addr) + addr = common.Address(addr) statelogger.Debugf("(+) %x\n", addr) diff --git a/tests/blocktest.go b/tests/blocktest.go index 6a9cf5f6d..0b923f08b 100644 --- a/tests/blocktest.go +++ b/tests/blocktest.go @@ -13,7 +13,7 @@ import ( "strings" "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/state" ) @@ -97,7 +97,7 @@ func LoadBlockTests(file string) (map[string]*BlockTest, error) { // InsertPreState populates the given database with the genesis // accounts defined by the test. -func (t *BlockTest) InsertPreState(db ethutil.Database) error { +func (t *BlockTest) InsertPreState(db common.Database) error { statedb := state.New(nil, db) for addrString, acct := range t.preAccounts { // XXX: is is worth it checking for errors here? diff --git a/tests/helper/common.go b/tests/helper/common.go index 6a071968d..21ea2261f 100644 --- a/tests/helper/common.go +++ b/tests/helper/common.go @@ -1,11 +1,11 @@ package helper -import "github.com/ethereum/go-ethereum/ethutil" +import "github.com/ethereum/go-ethereum/common" func FromHex(h string) []byte { - if ethutil.IsHex(h) { + if common.IsHex(h) { h = h[2:] } - return ethutil.Hex2Bytes(h) + return common.Hex2Bytes(h) } diff --git a/tests/helper/vm.go b/tests/helper/vm.go index f1aaf74b8..a7fd98696 100644 --- a/tests/helper/vm.go +++ b/tests/helper/vm.go @@ -6,7 +6,7 @@ import ( "github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/state" "github.com/ethereum/go-ethereum/vm" ) @@ -41,13 +41,13 @@ func NewEnv(state *state.StateDB) *Env { func NewEnvFromMap(state *state.StateDB, envValues map[string]string, exeValues map[string]string) *Env { env := NewEnv(state) - env.origin = ethutil.Hex2Bytes(exeValues["caller"]) - env.parent = ethutil.Hex2Bytes(envValues["previousHash"]) - env.coinbase = ethutil.Hex2Bytes(envValues["currentCoinbase"]) - env.number = ethutil.Big(envValues["currentNumber"]) - env.time = ethutil.Big(envValues["currentTimestamp"]).Int64() - env.difficulty = ethutil.Big(envValues["currentDifficulty"]) - env.gasLimit = ethutil.Big(envValues["currentGasLimit"]) + env.origin = common.Hex2Bytes(exeValues["caller"]) + env.parent = common.Hex2Bytes(envValues["previousHash"]) + env.coinbase = common.Hex2Bytes(envValues["currentCoinbase"]) + env.number = common.Big(envValues["currentNumber"]) + env.time = common.Big(envValues["currentTimestamp"]).Int64() + env.difficulty = common.Big(envValues["currentDifficulty"]) + env.gasLimit = common.Big(envValues["currentGasLimit"]) env.Gas = new(big.Int) return env @@ -135,9 +135,9 @@ func RunVm(state *state.StateDB, env, exec map[string]string) ([]byte, state.Log to = FromHex(exec["address"]) from = FromHex(exec["caller"]) data = FromHex(exec["data"]) - gas = ethutil.Big(exec["gas"]) - price = ethutil.Big(exec["gasPrice"]) - value = ethutil.Big(exec["value"]) + gas = common.Big(exec["gas"]) + price = common.Big(exec["gasPrice"]) + value = common.Big(exec["value"]) ) // Reset the pre-compiled contracts for VM tests. vm.Precompiled = make(map[string]*vm.PrecompiledAccount) @@ -155,12 +155,12 @@ func RunVm(state *state.StateDB, env, exec map[string]string) ([]byte, state.Log func RunState(statedb *state.StateDB, env, tx map[string]string) ([]byte, state.Logs, *big.Int, error) { var ( - keyPair, _ = crypto.NewKeyPairFromSec([]byte(ethutil.Hex2Bytes(tx["secretKey"]))) + keyPair, _ = crypto.NewKeyPairFromSec([]byte(common.Hex2Bytes(tx["secretKey"]))) to = FromHex(tx["to"]) data = FromHex(tx["data"]) - gas = ethutil.Big(tx["gasLimit"]) - price = ethutil.Big(tx["gasPrice"]) - value = ethutil.Big(tx["value"]) + gas = common.Big(tx["gasLimit"]) + price = common.Big(tx["gasPrice"]) + value = common.Big(tx["value"]) caddr = FromHex(env["currentCoinbase"]) ) @@ -169,7 +169,7 @@ func RunState(statedb *state.StateDB, env, tx map[string]string) ([]byte, state. snapshot := statedb.Copy() coinbase := statedb.GetOrNewStateObject(caddr) - coinbase.SetGasPool(ethutil.Big(env["currentGasLimit"])) + coinbase.SetGasPool(common.Big(env["currentGasLimit"])) message := NewMessage(keyPair.Address(), to, data, value, gas, price) vmenv := NewEnvFromMap(statedb, env, tx) diff --git a/tests/vm/gh_test.go b/tests/vm/gh_test.go index 1e8cd5b51..24718de7b 100644 --- a/tests/vm/gh_test.go +++ b/tests/vm/gh_test.go @@ -7,7 +7,7 @@ import ( "testing" "github.com/ethereum/go-ethereum/ethdb" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/state" "github.com/ethereum/go-ethereum/tests/helper" @@ -27,26 +27,26 @@ type Log struct { BloomF string `json:"bloom"` } -func (self Log) Address() []byte { return ethutil.Hex2Bytes(self.AddressF) } -func (self Log) Data() []byte { return ethutil.Hex2Bytes(self.DataF) } +func (self Log) Address() []byte { return common.Hex2Bytes(self.AddressF) } +func (self Log) Data() []byte { return common.Hex2Bytes(self.DataF) } func (self Log) RlpData() interface{} { return nil } func (self Log) Topics() [][]byte { t := make([][]byte, len(self.TopicsF)) for i, topic := range self.TopicsF { - t[i] = ethutil.Hex2Bytes(topic) + t[i] = common.Hex2Bytes(topic) } return t } -func StateObjectFromAccount(db ethutil.Database, addr string, account Account) *state.StateObject { - obj := state.NewStateObject(ethutil.Hex2Bytes(addr), db) - obj.SetBalance(ethutil.Big(account.Balance)) +func StateObjectFromAccount(db common.Database, addr string, account Account) *state.StateObject { + obj := state.NewStateObject(common.Hex2Bytes(addr), db) + obj.SetBalance(common.Big(account.Balance)) - if ethutil.IsHex(account.Code) { + if common.IsHex(account.Code) { account.Code = account.Code[2:] } - obj.SetCode(ethutil.Hex2Bytes(account.Code)) - obj.SetNonce(ethutil.Big(account.Nonce).Uint64()) + obj.SetCode(common.Hex2Bytes(account.Code)) + obj.SetNonce(common.Big(account.Nonce).Uint64()) return obj } @@ -86,7 +86,7 @@ func RunVmTest(p string, t *testing.T) { obj := StateObjectFromAccount(db, addr, account) statedb.SetStateObject(obj) for a, v := range account.Storage { - obj.SetState(helper.FromHex(a), ethutil.NewValue(helper.FromHex(v))) + obj.SetState(helper.FromHex(a), common.NewValue(helper.FromHex(v))) } } @@ -126,7 +126,7 @@ func RunVmTest(p string, t *testing.T) { if len(test.Gas) == 0 && err == nil { t.Errorf("%s's gas unspecified, indicating an error. VM returned (incorrectly) successfull", name) } else { - gexp := ethutil.Big(test.Gas) + gexp := common.Big(test.Gas) if gexp.Cmp(gas) != 0 { t.Errorf("%s's gas failed. Expected %v, got %v\n", name, gexp, gas) } @@ -140,8 +140,8 @@ func RunVmTest(p string, t *testing.T) { } if len(test.Exec) == 0 { - if obj.Balance().Cmp(ethutil.Big(account.Balance)) != 0 { - t.Errorf("%s's : (%x) balance failed. Expected %v, got %v => %v\n", name, obj.Address()[:4], account.Balance, obj.Balance(), new(big.Int).Sub(ethutil.Big(account.Balance), obj.Balance())) + if obj.Balance().Cmp(common.Big(account.Balance)) != 0 { + t.Errorf("%s's : (%x) balance failed. Expected %v, got %v => %v\n", name, obj.Address()[:4], account.Balance, obj.Balance(), new(big.Int).Sub(common.Big(account.Balance), obj.Balance())) } } @@ -150,14 +150,14 @@ func RunVmTest(p string, t *testing.T) { vexp := helper.FromHex(value) if bytes.Compare(v, vexp) != 0 { - t.Errorf("%s's : (%x: %s) storage failed. Expected %x, got %x (%v %v)\n", name, obj.Address()[0:4], addr, vexp, v, ethutil.BigD(vexp), ethutil.BigD(v)) + t.Errorf("%s's : (%x: %s) storage failed. Expected %x, got %x (%v %v)\n", name, obj.Address()[0:4], addr, vexp, v, common.BigD(vexp), common.BigD(v)) } } } if !isVmTest { statedb.Sync() - if !bytes.Equal(ethutil.Hex2Bytes(test.PostStateRoot), statedb.Root()) { + if !bytes.Equal(common.Hex2Bytes(test.PostStateRoot), statedb.Root()) { t.Errorf("%s's : Post state root error. Expected %s, got %x", name, test.PostStateRoot, statedb.Root()) } } @@ -170,8 +170,8 @@ func RunVmTest(p string, t *testing.T) { fmt.Println("A", test.Logs) fmt.Println("B", logs) for i, log := range test.Logs { - genBloom := ethutil.LeftPadBytes(types.LogsBloom(state.Logs{logs[i]}).Bytes(), 256) - if !bytes.Equal(genBloom, ethutil.Hex2Bytes(log.BloomF)) { + genBloom := common.LeftPadBytes(types.LogsBloom(state.Logs{logs[i]}).Bytes(), 256) + if !bytes.Equal(genBloom, common.Hex2Bytes(log.BloomF)) { t.Errorf("bloom mismatch") } } diff --git a/trie/hashnode.go b/trie/hashnode.go index e46628368..8125cc3c9 100644 --- a/trie/hashnode.go +++ b/trie/hashnode.go @@ -1,6 +1,6 @@ package trie -import "github.com/ethereum/go-ethereum/ethutil" +import "github.com/ethereum/go-ethereum/common" type HashNode struct { key []byte @@ -22,4 +22,4 @@ func (self *HashNode) Hash() interface{} { // These methods will never be called but we have to satisfy Node interface func (self *HashNode) Value() Node { return nil } func (self *HashNode) Dirty() bool { return true } -func (self *HashNode) Copy(t *Trie) Node { return NewHash(ethutil.CopyBytes(self.key), t) } +func (self *HashNode) Copy(t *Trie) Node { return NewHash(common.CopyBytes(self.key), t) } diff --git a/trie/shortnode.go b/trie/shortnode.go index d96492958..edd490b4d 100644 --- a/trie/shortnode.go +++ b/trie/shortnode.go @@ -1,6 +1,6 @@ package trie -import "github.com/ethereum/go-ethereum/ethutil" +import "github.com/ethereum/go-ethereum/common" type ShortNode struct { trie *Trie @@ -19,7 +19,7 @@ func (self *ShortNode) Value() Node { func (self *ShortNode) Dirty() bool { return true } func (self *ShortNode) Copy(t *Trie) Node { node := &ShortNode{t, nil, self.value.Copy(t)} - node.key = ethutil.CopyBytes(self.key) + node.key = common.CopyBytes(self.key) return node } diff --git a/trie/trie.go b/trie/trie.go index 9087f7bda..1c1112a7f 100644 --- a/trie/trie.go +++ b/trie/trie.go @@ -7,7 +7,7 @@ import ( "sync" "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" ) func ParanoiaCheck(t1 *Trie, backend Backend) (bool, *Trie) { @@ -39,7 +39,7 @@ func New(root []byte, backend Backend) *Trie { } if root != nil { - value := ethutil.NewValueFromBytes(trie.cache.Get(root)) + value := common.NewValueFromBytes(trie.cache.Get(root)) trie.root = trie.mknode(value) } @@ -71,10 +71,10 @@ func (self *Trie) Hash() []byte { if byts, ok := t.([]byte); ok && len(byts) > 0 { hash = byts } else { - hash = crypto.Sha3(ethutil.Encode(self.root.RlpData())) + hash = crypto.Sha3(common.Encode(self.root.RlpData())) } } else { - hash = crypto.Sha3(ethutil.Encode("")) + hash = crypto.Sha3(common.Encode("")) } if !bytes.Equal(hash, self.roothash) { @@ -105,7 +105,7 @@ func (self *Trie) Reset() { revision := self.revisions.Remove(self.revisions.Back()).([]byte) self.roothash = revision } - value := ethutil.NewValueFromBytes(self.cache.Get(self.roothash)) + value := common.NewValueFromBytes(self.cache.Get(self.roothash)) self.root = self.mknode(value) } @@ -294,7 +294,7 @@ func (self *Trie) delete(node Node, key []byte) Node { } // casting functions and cache storing -func (self *Trie) mknode(value *ethutil.Value) Node { +func (self *Trie) mknode(value *common.Value) Node { l := value.Len() switch l { case 0: @@ -320,7 +320,7 @@ func (self *Trie) mknode(value *ethutil.Value) Node { func (self *Trie) trans(node Node) Node { switch node := node.(type) { case *HashNode: - value := ethutil.NewValueFromBytes(self.cache.Get(node.key)) + value := common.NewValueFromBytes(self.cache.Get(node.key)) return self.mknode(value) default: return node @@ -328,7 +328,7 @@ func (self *Trie) trans(node Node) Node { } func (self *Trie) store(node Node) interface{} { - data := ethutil.Encode(node) + data := common.Encode(node) if len(data) >= 32 { key := crypto.Sha3(data) self.cache.Put(key, data) diff --git a/trie/trie_test.go b/trie/trie_test.go index b6a260483..1393e0c97 100644 --- a/trie/trie_test.go +++ b/trie/trie_test.go @@ -6,7 +6,7 @@ import ( "testing" "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" ) type Db map[string][]byte @@ -26,7 +26,7 @@ func NewEmptySecure() *SecureTrie { func TestEmptyTrie(t *testing.T) { trie := NewEmpty() res := trie.Hash() - exp := crypto.Sha3(ethutil.Encode("")) + exp := crypto.Sha3(common.Encode("")) if !bytes.Equal(res, exp) { t.Errorf("expected %x got %x", exp, res) } @@ -39,7 +39,7 @@ func TestInsert(t *testing.T) { trie.UpdateString("dog", "puppy") trie.UpdateString("dogglesworth", "cat") - exp := ethutil.Hex2Bytes("8aad789dff2f538bca5d8ea56e8abe10f4c7ba3a5dea95fea4cd6e7c3a1168d3") + exp := common.Hex2Bytes("8aad789dff2f538bca5d8ea56e8abe10f4c7ba3a5dea95fea4cd6e7c3a1168d3") root := trie.Hash() if !bytes.Equal(root, exp) { t.Errorf("exp %x got %x", exp, root) @@ -48,7 +48,7 @@ func TestInsert(t *testing.T) { trie = NewEmpty() trie.UpdateString("A", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") - exp = ethutil.Hex2Bytes("d23786fb4a010da3ce639d66d5e904a11dbc02746d1ce25029e53290cabf28ab") + exp = common.Hex2Bytes("d23786fb4a010da3ce639d66d5e904a11dbc02746d1ce25029e53290cabf28ab") root = trie.Hash() if !bytes.Equal(root, exp) { t.Errorf("exp %x got %x", exp, root) @@ -95,7 +95,7 @@ func TestDelete(t *testing.T) { } hash := trie.Hash() - exp := ethutil.Hex2Bytes("5991bb8c6514148a29db676a14ac506cd2cd5775ace63c30a4fe457715e9ac84") + exp := common.Hex2Bytes("5991bb8c6514148a29db676a14ac506cd2cd5775ace63c30a4fe457715e9ac84") if !bytes.Equal(hash, exp) { t.Errorf("expected %x got %x", exp, hash) } @@ -119,7 +119,7 @@ func TestEmptyValues(t *testing.T) { } hash := trie.Hash() - exp := ethutil.Hex2Bytes("5991bb8c6514148a29db676a14ac506cd2cd5775ace63c30a4fe457715e9ac84") + exp := common.Hex2Bytes("5991bb8c6514148a29db676a14ac506cd2cd5775ace63c30a4fe457715e9ac84") if !bytes.Equal(hash, exp) { t.Errorf("expected %x got %x", exp, hash) } @@ -168,7 +168,7 @@ func TestReset(t *testing.T) { } trie.Commit() - before := ethutil.CopyBytes(trie.roothash) + before := common.CopyBytes(trie.roothash) trie.UpdateString("should", "revert") trie.Hash() // Should have no effect @@ -177,7 +177,7 @@ func TestReset(t *testing.T) { // ### trie.Reset() - after := ethutil.CopyBytes(trie.roothash) + after := common.CopyBytes(trie.roothash) if !bytes.Equal(before, after) { t.Errorf("expected roots to be equal. %x - %x", before, after) @@ -272,8 +272,8 @@ func TestLargeData(t *testing.T) { vals := make(map[string]*kv) for i := byte(0); i < 255; i++ { - value := &kv{ethutil.LeftPadBytes([]byte{i}, 32), []byte{i}, false} - value2 := &kv{ethutil.LeftPadBytes([]byte{10, i}, 32), []byte{i}, false} + value := &kv{common.LeftPadBytes([]byte{i}, 32), []byte{i}, false} + value2 := &kv{common.LeftPadBytes([]byte{10, i}, 32), []byte{i}, false} trie.Update(value.k, value.v) trie.Update(value2.k, value2.v) vals[string(value.k)] = value @@ -322,7 +322,7 @@ func TestSecureDelete(t *testing.T) { } hash := trie.Hash() - exp := ethutil.Hex2Bytes("29b235a58c3c25ab83010c327d5932bcf05324b7d6b1185e650798034783ca9d") + exp := common.Hex2Bytes("29b235a58c3c25ab83010c327d5932bcf05324b7d6b1185e650798034783ca9d") if !bytes.Equal(hash, exp) { t.Errorf("expected %x got %x", exp, hash) } diff --git a/trie/valuenode.go b/trie/valuenode.go index 8912b1c82..7bf8ff06e 100644 --- a/trie/valuenode.go +++ b/trie/valuenode.go @@ -1,6 +1,6 @@ package trie -import "github.com/ethereum/go-ethereum/ethutil" +import "github.com/ethereum/go-ethereum/common" type ValueNode struct { trie *Trie @@ -10,6 +10,6 @@ type ValueNode struct { func (self *ValueNode) Value() Node { return self } // Best not to call :-) func (self *ValueNode) Val() []byte { return self.data } func (self *ValueNode) Dirty() bool { return true } -func (self *ValueNode) Copy(t *Trie) Node { return &ValueNode{t, ethutil.CopyBytes(self.data)} } +func (self *ValueNode) Copy(t *Trie) Node { return &ValueNode{t, common.CopyBytes(self.data)} } func (self *ValueNode) RlpData() interface{} { return self.data } func (self *ValueNode) Hash() interface{} { return self.data } diff --git a/ui/qt/qwhisper/message.go b/ui/qt/qwhisper/message.go index 26e72ac93..f8bed8a2d 100644 --- a/ui/qt/qwhisper/message.go +++ b/ui/qt/qwhisper/message.go @@ -2,7 +2,7 @@ package qwhisper import ( "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/whisper" ) @@ -17,7 +17,7 @@ func ToQMessage(msg *whisper.Message) *Message { return &Message{ ref: msg, Flags: int32(msg.Flags), - Payload: "0x" + ethutil.Bytes2Hex(msg.Payload), - From: "0x" + ethutil.Bytes2Hex(crypto.FromECDSAPub(msg.Recover())), + Payload: "0x" + common.Bytes2Hex(msg.Payload), + From: "0x" + common.Bytes2Hex(crypto.FromECDSAPub(msg.Recover())), } } diff --git a/ui/qt/qwhisper/whisper.go b/ui/qt/qwhisper/whisper.go index 7fef1929f..90ec822aa 100644 --- a/ui/qt/qwhisper/whisper.go +++ b/ui/qt/qwhisper/whisper.go @@ -5,7 +5,7 @@ import ( "time" "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/whisper" "github.com/obscuren/qml" @@ -13,7 +13,7 @@ import ( var qlogger = logger.NewLogger("QSHH") -func toHex(b []byte) string { return "0x" + ethutil.Bytes2Hex(b) } +func toHex(b []byte) string { return "0x" + common.Bytes2Hex(b) } type Whisper struct { *whisper.Whisper @@ -33,15 +33,15 @@ func (self *Whisper) SetView(view qml.Object) { func (self *Whisper) Post(payload []string, to, from string, topics []string, priority, ttl uint32) { var data []byte for _, d := range payload { - data = append(data, ethutil.FromHex(d)...) + data = append(data, common.FromHex(d)...) } - pk := crypto.ToECDSAPub(ethutil.FromHex(from)) + pk := crypto.ToECDSAPub(common.FromHex(from)) if key := self.Whisper.GetIdentity(pk); key != nil { msg := whisper.NewMessage(data) envelope, err := msg.Seal(time.Duration(priority*100000), whisper.Opts{ Ttl: time.Duration(ttl) * time.Second, - To: crypto.ToECDSAPub(ethutil.FromHex(to)), + To: crypto.ToECDSAPub(common.FromHex(to)), From: key, Topics: whisper.TopicsFromString(topics...), }) @@ -70,7 +70,7 @@ func (self *Whisper) NewIdentity() string { } func (self *Whisper) HasIdentity(key string) bool { - return self.Whisper.HasIdentity(crypto.ToECDSAPub(ethutil.FromHex(key))) + return self.Whisper.HasIdentity(crypto.ToECDSAPub(common.FromHex(key))) } func (self *Whisper) Watch(opts map[string]interface{}, view *qml.Common) int { @@ -88,9 +88,9 @@ func (self *Whisper) Watch(opts map[string]interface{}, view *qml.Common) int { return i } -func (self *Whisper) Messages(id int) (messages *ethutil.List) { +func (self *Whisper) Messages(id int) (messages *common.List) { msgs := self.Whisper.Messages(id) - messages = ethutil.EmptyList() + messages = common.EmptyList() for _, message := range msgs { messages.Append(ToQMessage(message)) } @@ -100,10 +100,10 @@ func (self *Whisper) Messages(id int) (messages *ethutil.List) { func filterFromMap(opts map[string]interface{}) (f whisper.Filter) { if to, ok := opts["to"].(string); ok { - f.To = crypto.ToECDSAPub(ethutil.FromHex(to)) + f.To = crypto.ToECDSAPub(common.FromHex(to)) } if from, ok := opts["from"].(string); ok { - f.From = crypto.ToECDSAPub(ethutil.FromHex(from)) + f.From = crypto.ToECDSAPub(common.FromHex(from)) } if topicList, ok := opts["topics"].(*qml.List); ok { var topics []string diff --git a/vm/address.go b/vm/address.go index b1345da8f..215f4bc8f 100644 --- a/vm/address.go +++ b/vm/address.go @@ -4,7 +4,7 @@ import ( "math/big" "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" ) type Address interface { @@ -26,25 +26,25 @@ var Precompiled = PrecompiledContracts() func PrecompiledContracts() map[string]*PrecompiledAccount { return map[string]*PrecompiledAccount{ // ECRECOVER - string(ethutil.LeftPadBytes([]byte{1}, 20)): &PrecompiledAccount{func(l int) *big.Int { + string(common.LeftPadBytes([]byte{1}, 20)): &PrecompiledAccount{func(l int) *big.Int { return GasEcrecover }, ecrecoverFunc}, // SHA256 - string(ethutil.LeftPadBytes([]byte{2}, 20)): &PrecompiledAccount{func(l int) *big.Int { + string(common.LeftPadBytes([]byte{2}, 20)): &PrecompiledAccount{func(l int) *big.Int { n := big.NewInt(int64(l+31) / 32) n.Mul(n, GasSha256Word) return n.Add(n, GasSha256Base) }, sha256Func}, // RIPEMD160 - string(ethutil.LeftPadBytes([]byte{3}, 20)): &PrecompiledAccount{func(l int) *big.Int { + string(common.LeftPadBytes([]byte{3}, 20)): &PrecompiledAccount{func(l int) *big.Int { n := big.NewInt(int64(l+31) / 32) n.Mul(n, GasRipemdWord) return n.Add(n, GasRipemdBase) }, ripemd160Func}, - string(ethutil.LeftPadBytes([]byte{4}, 20)): &PrecompiledAccount{func(l int) *big.Int { + string(common.LeftPadBytes([]byte{4}, 20)): &PrecompiledAccount{func(l int) *big.Int { n := big.NewInt(int64(l+31) / 32) n.Mul(n, GasIdentityWord) @@ -58,7 +58,7 @@ func sha256Func(in []byte) []byte { } func ripemd160Func(in []byte) []byte { - return ethutil.LeftPadBytes(crypto.Ripemd160(in), 32) + return common.LeftPadBytes(crypto.Ripemd160(in), 32) } func ecrecoverFunc(in []byte) []byte { @@ -66,10 +66,10 @@ func ecrecoverFunc(in []byte) []byte { defer func() { recover() }() hash := in[:32] - v := ethutil.BigD(in[32:64]).Bytes()[0] - 27 + v := common.BigD(in[32:64]).Bytes()[0] - 27 sig := append(in[64:], v) - return ethutil.LeftPadBytes(crypto.Sha3(crypto.Ecrecover(append(hash, sig...))[1:])[12:], 32) + return common.LeftPadBytes(crypto.Sha3(crypto.Ecrecover(append(hash, sig...))[1:])[12:], 32) } func memCpy(in []byte) []byte { diff --git a/vm/asm.go b/vm/asm.go index a94f01d3d..83fcb0e08 100644 --- a/vm/asm.go +++ b/vm/asm.go @@ -4,7 +4,7 @@ import ( "fmt" "math/big" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" ) func Disassemble(script []byte) (asm []string) { @@ -23,7 +23,7 @@ func Disassemble(script []byte) (asm []string) { switch op { case PUSH1, PUSH2, PUSH3, PUSH4, PUSH5, PUSH6, PUSH7, PUSH8, PUSH9, PUSH10, PUSH11, PUSH12, PUSH13, PUSH14, PUSH15, PUSH16, PUSH17, PUSH18, PUSH19, PUSH20, PUSH21, PUSH22, PUSH23, PUSH24, PUSH25, PUSH26, PUSH27, PUSH28, PUSH29, PUSH30, PUSH31, PUSH32: - pc.Add(pc, ethutil.Big1) + pc.Add(pc, common.Big1) a := int64(op) - int64(PUSH1) + 1 if int(pc.Int64()+a) > len(script) { return nil @@ -38,7 +38,7 @@ func Disassemble(script []byte) (asm []string) { pc.Add(pc, big.NewInt(a-1)) } - pc.Add(pc, ethutil.Big1) + pc.Add(pc, common.Big1) } return diff --git a/vm/common.go b/vm/common.go index 1cb549228..1f07ec8a2 100644 --- a/vm/common.go +++ b/vm/common.go @@ -4,7 +4,7 @@ import ( "math" "math/big" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/logger" ) @@ -82,22 +82,22 @@ var ( GasIdentityWord = big.NewInt(3) GasCopyWord = big.NewInt(3) - Pow256 = ethutil.BigPow(2, 256) + Pow256 = common.BigPow(2, 256) LogTyPretty byte = 0x1 LogTyDiff byte = 0x2 - U256 = ethutil.U256 - S256 = ethutil.S256 + U256 = common.U256 + S256 = common.S256 - Zero = ethutil.Big0 + Zero = common.Big0 ) const MaxCallDepth = 1025 func calcMemSize(off, l *big.Int) *big.Int { - if l.Cmp(ethutil.Big0) == 0 { - return ethutil.Big0 + if l.Cmp(common.Big0) == 0 { + return common.Big0 } return new(big.Int).Add(off, l) @@ -123,5 +123,5 @@ func getCode(code []byte, start, size uint64) []byte { x := uint64(math.Min(float64(start), float64(len(code)))) y := uint64(math.Min(float64(x+size), float64(len(code)))) - return ethutil.RightPadBytes(code[x:y], int(size)) + return common.RightPadBytes(code[x:y], int(size)) } diff --git a/vm/context.go b/vm/context.go index 78712f561..6edde0824 100644 --- a/vm/context.go +++ b/vm/context.go @@ -4,7 +4,7 @@ import ( "math" "math/big" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" ) type ContextRef interface { @@ -61,7 +61,7 @@ func (c *Context) GetRangeValue(x, size uint64) []byte { x = uint64(math.Min(float64(x), float64(len(c.Code)))) y := uint64(math.Min(float64(x+size), float64(len(c.Code)))) - return ethutil.RightPadBytes(c.Code[x:y], int(size)) + return common.RightPadBytes(c.Code[x:y], int(size)) } func (c *Context) GetCode(x, size uint64) []byte { diff --git a/vm/environment.go b/vm/environment.go index 69832241f..83faaa23e 100644 --- a/vm/environment.go +++ b/vm/environment.go @@ -5,7 +5,7 @@ import ( "fmt" "math/big" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/state" ) @@ -76,7 +76,7 @@ func (self *Log) Number() uint64 { } func (self *Log) RlpData() interface{} { - return []interface{}{self.address, ethutil.ByteSliceToInterface(self.topics), self.data} + return []interface{}{self.address, common.ByteSliceToInterface(self.topics), self.data} } func (self *Log) String() string { diff --git a/vm/vm.go b/vm/vm.go index 58aebeedb..4d9e88e1a 100644 --- a/vm/vm.go +++ b/vm/vm.go @@ -5,7 +5,7 @@ import ( "math/big" "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/state" ) @@ -160,7 +160,7 @@ func (self *Vm) Run(context *Context, callData []byte) (ret []byte, err error) { x, y := stack.pop(), stack.pop() self.Printf(" %v / %v", x, y) - if y.Cmp(ethutil.Big0) != 0 { + if y.Cmp(common.Big0) != 0 { base.Div(x, y) } @@ -174,11 +174,11 @@ func (self *Vm) Run(context *Context, callData []byte) (ret []byte, err error) { self.Printf(" %v / %v", x, y) - if y.Cmp(ethutil.Big0) == 0 { - base.Set(ethutil.Big0) + if y.Cmp(common.Big0) == 0 { + base.Set(common.Big0) } else { n := new(big.Int) - if new(big.Int).Mul(x, y).Cmp(ethutil.Big0) < 0 { + if new(big.Int).Mul(x, y).Cmp(common.Big0) < 0 { n.SetInt64(-1) } else { n.SetInt64(1) @@ -196,8 +196,8 @@ func (self *Vm) Run(context *Context, callData []byte) (ret []byte, err error) { self.Printf(" %v %% %v", x, y) - if y.Cmp(ethutil.Big0) == 0 { - base.Set(ethutil.Big0) + if y.Cmp(common.Big0) == 0 { + base.Set(common.Big0) } else { base.Mod(x, y) } @@ -211,11 +211,11 @@ func (self *Vm) Run(context *Context, callData []byte) (ret []byte, err error) { self.Printf(" %v %% %v", x, y) - if y.Cmp(ethutil.Big0) == 0 { - base.Set(ethutil.Big0) + if y.Cmp(common.Big0) == 0 { + base.Set(common.Big0) } else { n := new(big.Int) - if x.Cmp(ethutil.Big0) < 0 { + if x.Cmp(common.Big0) < 0 { n.SetInt64(-1) } else { n.SetInt64(1) @@ -246,9 +246,9 @@ func (self *Vm) Run(context *Context, callData []byte) (ret []byte, err error) { if back.Cmp(big.NewInt(31)) < 0 { bit := uint(back.Uint64()*8 + 7) num := stack.pop() - mask := new(big.Int).Lsh(ethutil.Big1, bit) - mask.Sub(mask, ethutil.Big1) - if ethutil.BitTest(num, int(bit)) { + mask := new(big.Int).Lsh(common.Big1, bit) + mask.Sub(mask, common.Big1) + if common.BitTest(num, int(bit)) { num.Or(num, mask.Not(mask)) } else { num.And(num, mask) @@ -262,7 +262,7 @@ func (self *Vm) Run(context *Context, callData []byte) (ret []byte, err error) { } case NOT: stack.push(U256(new(big.Int).Not(stack.pop()))) - //base.Sub(Pow256, stack.pop()).Sub(base, ethutil.Big1) + //base.Sub(Pow256, stack.pop()).Sub(base, common.Big1) //base = U256(base) //stack.push(base) case LT: @@ -270,9 +270,9 @@ func (self *Vm) Run(context *Context, callData []byte) (ret []byte, err error) { self.Printf(" %v < %v", x, y) // x < y if x.Cmp(y) < 0 { - stack.push(ethutil.BigTrue) + stack.push(common.BigTrue) } else { - stack.push(ethutil.BigFalse) + stack.push(common.BigFalse) } case GT: x, y := stack.pop(), stack.pop() @@ -280,9 +280,9 @@ func (self *Vm) Run(context *Context, callData []byte) (ret []byte, err error) { // x > y if x.Cmp(y) > 0 { - stack.push(ethutil.BigTrue) + stack.push(common.BigTrue) } else { - stack.push(ethutil.BigFalse) + stack.push(common.BigFalse) } case SLT: @@ -290,9 +290,9 @@ func (self *Vm) Run(context *Context, callData []byte) (ret []byte, err error) { self.Printf(" %v < %v", x, y) // x < y if x.Cmp(S256(y)) < 0 { - stack.push(ethutil.BigTrue) + stack.push(common.BigTrue) } else { - stack.push(ethutil.BigFalse) + stack.push(common.BigFalse) } case SGT: x, y := S256(stack.pop()), S256(stack.pop()) @@ -300,9 +300,9 @@ func (self *Vm) Run(context *Context, callData []byte) (ret []byte, err error) { // x > y if x.Cmp(y) > 0 { - stack.push(ethutil.BigTrue) + stack.push(common.BigTrue) } else { - stack.push(ethutil.BigFalse) + stack.push(common.BigFalse) } case EQ: @@ -311,16 +311,16 @@ func (self *Vm) Run(context *Context, callData []byte) (ret []byte, err error) { // x == y if x.Cmp(y) == 0 { - stack.push(ethutil.BigTrue) + stack.push(common.BigTrue) } else { - stack.push(ethutil.BigFalse) + stack.push(common.BigFalse) } case ISZERO: x := stack.pop() - if x.Cmp(ethutil.BigFalse) > 0 { - stack.push(ethutil.BigFalse) + if x.Cmp(common.BigFalse) > 0 { + stack.push(common.BigFalse) } else { - stack.push(ethutil.BigTrue) + stack.push(common.BigTrue) } // 0x10 range @@ -343,11 +343,11 @@ func (self *Vm) Run(context *Context, callData []byte) (ret []byte, err error) { th, val := stack.pop(), stack.pop() if th.Cmp(big.NewInt(32)) < 0 { - byt := big.NewInt(int64(ethutil.LeftPadBytes(val.Bytes(), 32)[th.Int64()])) + byt := big.NewInt(int64(common.LeftPadBytes(val.Bytes(), 32)[th.Int64()])) base.Set(byt) } else { - base.Set(ethutil.BigFalse) + base.Set(common.BigFalse) } self.Printf(" => 0x%x", base.Bytes()) @@ -389,12 +389,12 @@ func (self *Vm) Run(context *Context, callData []byte) (ret []byte, err error) { offset, size := stack.pop(), stack.pop() data := crypto.Sha3(mem.Get(offset.Int64(), size.Int64())) - stack.push(ethutil.BigD(data)) + stack.push(common.BigD(data)) self.Printf(" => (%v) %x", size, data) // 0x30 range case ADDRESS: - stack.push(ethutil.BigD(context.Address())) + stack.push(common.BigD(context.Address())) self.Printf(" => %x", context.Address()) case BALANCE: @@ -407,12 +407,12 @@ func (self *Vm) Run(context *Context, callData []byte) (ret []byte, err error) { case ORIGIN: origin := self.env.Origin() - stack.push(ethutil.BigD(origin)) + stack.push(common.BigD(origin)) self.Printf(" => %x", origin) case CALLER: caller := context.caller.Address() - stack.push(ethutil.BigD(caller)) + stack.push(common.BigD(caller)) self.Printf(" => %x", caller) case CALLVALUE: @@ -427,15 +427,15 @@ func (self *Vm) Run(context *Context, callData []byte) (ret []byte, err error) { ) if lenData.Cmp(offset) >= 0 { - length := new(big.Int).Add(offset, ethutil.Big32) - length = ethutil.BigMin(length, lenData) + length := new(big.Int).Add(offset, common.Big32) + length = common.BigMin(length, lenData) copy(data, callData[offset.Int64():length.Int64()]) } self.Printf(" => 0x%x", data) - stack.push(ethutil.BigD(data)) + stack.push(common.BigD(data)) case CALLDATASIZE: l := int64(len(callData)) stack.push(big.NewInt(l)) @@ -501,18 +501,18 @@ func (self *Vm) Run(context *Context, callData []byte) (ret []byte, err error) { case BLOCKHASH: num := stack.pop() - n := new(big.Int).Sub(self.env.BlockNumber(), ethutil.Big257) + n := new(big.Int).Sub(self.env.BlockNumber(), common.Big257) if num.Cmp(n) > 0 && num.Cmp(self.env.BlockNumber()) < 0 { - stack.push(ethutil.BigD(self.env.GetHash(num.Uint64()))) + stack.push(common.BigD(self.env.GetHash(num.Uint64()))) } else { - stack.push(ethutil.Big0) + stack.push(common.Big0) } self.Printf(" => 0x%x", stack.peek().Bytes()) case COINBASE: coinbase := self.env.Coinbase() - stack.push(ethutil.BigD(coinbase)) + stack.push(common.BigD(coinbase)) self.Printf(" => 0x%x", coinbase) case TIMESTAMP: @@ -543,7 +543,7 @@ func (self *Vm) Run(context *Context, callData []byte) (ret []byte, err error) { a := uint64(op - PUSH1 + 1) byts := context.GetRangeValue(pc+1, a) // push value to stack - stack.push(ethutil.BigD(byts)) + stack.push(common.BigD(byts)) pc += a step += int(op) - int(PUSH1) + 1 @@ -566,7 +566,7 @@ func (self *Vm) Run(context *Context, callData []byte) (ret []byte, err error) { topics := make([][]byte, n) mStart, mSize := stack.pop(), stack.pop() for i := 0; i < n; i++ { - topics[i] = ethutil.LeftPadBytes(stack.pop().Bytes(), 32) + topics[i] = common.LeftPadBytes(stack.pop().Bytes(), 32) } data := mem.Get(mStart.Int64(), mSize.Int64()) @@ -576,14 +576,14 @@ func (self *Vm) Run(context *Context, callData []byte) (ret []byte, err error) { self.Printf(" => %v", log) case MLOAD: offset := stack.pop() - val := ethutil.BigD(mem.Get(offset.Int64(), 32)) + val := common.BigD(mem.Get(offset.Int64(), 32)) stack.push(val) self.Printf(" => 0x%x", val.Bytes()) case MSTORE: // Store the value at stack top-1 in to memory at location stack top // pop value of the stack mStart, val := stack.pop(), stack.pop() - mem.Set(mStart.Uint64(), 32, ethutil.BigToBytes(val, 256)) + mem.Set(mStart.Uint64(), 32, common.BigToBytes(val, 256)) self.Printf(" => 0x%x", val) case MSTORE8: @@ -594,7 +594,7 @@ func (self *Vm) Run(context *Context, callData []byte) (ret []byte, err error) { self.Printf(" => [%v] 0x%x", off, val) case SLOAD: loc := stack.pop() - val := ethutil.BigD(statedb.GetState(context.Address(), loc.Bytes())) + val := common.BigD(statedb.GetState(context.Address(), loc.Bytes())) stack.push(val) self.Printf(" {0x%x : 0x%x}", loc.Bytes(), val.Bytes()) @@ -610,7 +610,7 @@ func (self *Vm) Run(context *Context, callData []byte) (ret []byte, err error) { case JUMPI: pos, cond := stack.pop(), stack.pop() - if cond.Cmp(ethutil.BigTrue) >= 0 { + if cond.Cmp(common.BigTrue) >= 0 { jump(pc, pos) continue @@ -642,7 +642,7 @@ func (self *Vm) Run(context *Context, callData []byte) (ret []byte, err error) { context.UseGas(context.Gas) ret, suberr, ref := self.env.Create(context, nil, input, gas, price, value) if suberr != nil { - stack.push(ethutil.BigFalse) + stack.push(common.BigFalse) self.Printf(" (*) 0x0 %v", suberr) } else { @@ -655,7 +655,7 @@ func (self *Vm) Run(context *Context, callData []byte) (ret []byte, err error) { } addr = ref.Address() - stack.push(ethutil.BigD(addr)) + stack.push(common.BigD(addr)) } @@ -669,7 +669,7 @@ func (self *Vm) Run(context *Context, callData []byte) (ret []byte, err error) { // pop return size and offset retOffset, retSize := stack.pop(), stack.pop() - address := ethutil.Address(addr.Bytes()) + address := common.Address(addr.Bytes()) self.Printf(" => %x", address).Endl() // Get the arguments from the memory @@ -690,11 +690,11 @@ func (self *Vm) Run(context *Context, callData []byte) (ret []byte, err error) { } if err != nil { - stack.push(ethutil.BigFalse) + stack.push(common.BigFalse) self.Printf("%v").Endl() } else { - stack.push(ethutil.BigTrue) + stack.push(common.BigTrue) mem.Set(retOffset.Uint64(), retSize.Uint64(), ret) } @@ -834,21 +834,21 @@ func (self *Vm) calculateGasAndSize(context *Context, caller ContextRef, op OpCo x := calcMemSize(stack.data[stack.len()-6], stack.data[stack.len()-7]) y := calcMemSize(stack.data[stack.len()-4], stack.data[stack.len()-5]) - newMemSize = ethutil.BigMax(x, y) + newMemSize = common.BigMax(x, y) } - if newMemSize.Cmp(ethutil.Big0) > 0 { + if newMemSize.Cmp(common.Big0) > 0 { newMemSizeWords := toWordSize(newMemSize) newMemSize.Mul(newMemSizeWords, u256(32)) if newMemSize.Cmp(u256(int64(mem.Len()))) > 0 { oldSize := toWordSize(big.NewInt(int64(mem.Len()))) - pow := new(big.Int).Exp(oldSize, ethutil.Big2, Zero) + pow := new(big.Int).Exp(oldSize, common.Big2, Zero) linCoef := new(big.Int).Mul(oldSize, GasMemWord) quadCoef := new(big.Int).Div(pow, GasQuadCoeffDenom) oldTotalFee := new(big.Int).Add(linCoef, quadCoef) - pow.Exp(newMemSizeWords, ethutil.Big2, Zero) + pow.Exp(newMemSizeWords, common.Big2, Zero) linCoef = new(big.Int).Mul(newMemSizeWords, GasMemWord) quadCoef = new(big.Int).Div(pow, GasQuadCoeffDenom) newTotalFee := new(big.Int).Add(linCoef, quadCoef) diff --git a/whisper/envelope.go b/whisper/envelope.go index d30397c98..577638046 100644 --- a/whisper/envelope.go +++ b/whisper/envelope.go @@ -8,7 +8,7 @@ import ( "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto/ecies" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/rlp" ) @@ -28,7 +28,7 @@ type Envelope struct { func (self *Envelope) Hash() Hash { if self.hash == EmptyHash { - self.hash = H(crypto.Sha3(ethutil.Encode(self))) + self.hash = H(crypto.Sha3(common.Encode(self))) } return self.hash @@ -76,14 +76,14 @@ func (self *Envelope) Open(prv *ecdsa.PrivateKey) (msg *Message, err error) { func (self *Envelope) proveWork(dura time.Duration) { var bestBit int d := make([]byte, 64) - copy(d[:32], ethutil.Encode(self.withoutNonce())) + copy(d[:32], common.Encode(self.withoutNonce())) then := time.Now().Add(dura).UnixNano() for n := uint32(0); time.Now().UnixNano() < then; { for i := 0; i < 1024; i++ { binary.BigEndian.PutUint32(d[60:], n) - fbs := ethutil.FirstBitSet(ethutil.BigD(crypto.Sha3(d))) + fbs := common.FirstBitSet(common.BigD(crypto.Sha3(d))) if fbs > bestBit { bestBit = fbs self.Nonce = n @@ -96,17 +96,17 @@ func (self *Envelope) proveWork(dura time.Duration) { func (self *Envelope) valid() bool { d := make([]byte, 64) - copy(d[:32], ethutil.Encode(self.withoutNonce())) + copy(d[:32], common.Encode(self.withoutNonce())) binary.BigEndian.PutUint32(d[60:], self.Nonce) - return ethutil.FirstBitSet(ethutil.BigD(crypto.Sha3(d))) > 0 + return common.FirstBitSet(common.BigD(crypto.Sha3(d))) > 0 } func (self *Envelope) withoutNonce() interface{} { - return []interface{}{self.Expiry, self.Ttl, ethutil.ByteSliceToInterface(self.Topics), self.Data} + return []interface{}{self.Expiry, self.Ttl, common.ByteSliceToInterface(self.Topics), self.Data} } func (self *Envelope) RlpData() interface{} { - return []interface{}{self.Expiry, self.Ttl, ethutil.ByteSliceToInterface(self.Topics), self.Data, self.Nonce} + return []interface{}{self.Expiry, self.Ttl, common.ByteSliceToInterface(self.Topics), self.Data, self.Nonce} } func (self *Envelope) DecodeRLP(s *rlp.Stream) error { @@ -128,7 +128,7 @@ func (self *Envelope) DecodeRLP(s *rlp.Stream) error { self.Nonce = extenv.Nonce // TODO We should use the stream directly here. - self.hash = H(crypto.Sha3(ethutil.Encode(self))) + self.hash = H(crypto.Sha3(common.Encode(self))) return nil } diff --git a/xeth/state.go b/xeth/state.go index bb729db33..7d9ceab1b 100644 --- a/xeth/state.go +++ b/xeth/state.go @@ -1,7 +1,7 @@ package xeth import ( - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/state" ) @@ -19,7 +19,7 @@ func (self *State) State() *state.StateDB { } func (self *State) Get(addr string) *Object { - return &Object{self.state.GetStateObject(ethutil.FromHex(addr))} + return &Object{self.state.GetStateObject(common.FromHex(addr))} } func (self *State) SafeGet(addr string) *Object { @@ -27,9 +27,9 @@ func (self *State) SafeGet(addr string) *Object { } func (self *State) safeGet(addr string) *state.StateObject { - object := self.state.GetStateObject(ethutil.FromHex(addr)) + object := self.state.GetStateObject(common.FromHex(addr)) if object == nil { - object = state.NewStateObject(ethutil.FromHex(addr), self.xeth.eth.StateDb()) + object = state.NewStateObject(common.FromHex(addr), self.xeth.eth.StateDb()) } return object diff --git a/xeth/types.go b/xeth/types.go index 3dc25a2ea..e15305481 100644 --- a/xeth/types.go +++ b/xeth/types.go @@ -8,14 +8,14 @@ import ( "github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/p2p" "github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/state" ) func toHex(b []byte) string { - return "0x" + ethutil.Bytes2Hex(b) + return "0x" + common.Bytes2Hex(b) } type Object struct { @@ -26,20 +26,20 @@ func NewObject(state *state.StateObject) *Object { return &Object{state} } -func (self *Object) StorageString(str string) *ethutil.Value { - if ethutil.IsHex(str) { - return self.storage(ethutil.Hex2Bytes(str[2:])) +func (self *Object) StorageString(str string) *common.Value { + if common.IsHex(str) { + return self.storage(common.Hex2Bytes(str[2:])) } else { - return self.storage(ethutil.RightPadBytes([]byte(str), 32)) + return self.storage(common.RightPadBytes([]byte(str), 32)) } } -func (self *Object) StorageValue(addr *ethutil.Value) *ethutil.Value { +func (self *Object) StorageValue(addr *common.Value) *common.Value { return self.storage(addr.Bytes()) } -func (self *Object) storage(addr []byte) *ethutil.Value { - return self.StateObject.GetStorage(ethutil.BigD(addr)) +func (self *Object) storage(addr []byte) *common.Value { + return self.StateObject.GetStorage(common.BigD(addr)) } func (self *Object) Storage() (storage map[string]string) { @@ -62,8 +62,8 @@ type Block struct { Size string `json:"size"` Number int `json:"number"` Hash string `json:"hash"` - Transactions *ethutil.List `json:"transactions"` - Uncles *ethutil.List `json:"uncles"` + Transactions *common.List `json:"transactions"` + Uncles *common.List `json:"uncles"` Time int64 `json:"time"` Coinbase string `json:"coinbase"` Name string `json:"name"` @@ -84,13 +84,13 @@ func NewBlock(block *types.Block) *Block { for i, tx := range block.Transactions() { ptxs[i] = NewTx(tx) } - txlist := ethutil.NewList(ptxs) + txlist := common.NewList(ptxs) puncles := make([]*Block, len(block.Uncles())) for i, uncle := range block.Uncles() { puncles[i] = NewBlock(types.NewBlockWithHeader(uncle)) } - ulist := ethutil.NewList(puncles) + ulist := common.NewList(puncles) return &Block{ ref: block, Size: block.Size().String(), @@ -114,7 +114,7 @@ func (self *Block) ToString() string { } func (self *Block) GetTransaction(hash string) *Transaction { - tx := self.ref.Transaction(ethutil.FromHex(hash)) + tx := self.ref.Transaction(common.FromHex(hash)) if tx == nil { return nil } @@ -154,7 +154,7 @@ func NewTx(tx *types.Transaction) *Transaction { data = toHex(tx.Data()) } - return &Transaction{ref: tx, Hash: hash, Value: ethutil.CurrencyToString(tx.Value()), Address: receiver, Contract: createsContract, Gas: tx.Gas().String(), GasPrice: tx.GasPrice().String(), Data: data, Sender: sender, CreatesContract: createsContract, RawData: toHex(tx.Data())} + return &Transaction{ref: tx, Hash: hash, Value: common.CurrencyToString(tx.Value()), Address: receiver, Contract: createsContract, Gas: tx.Gas().String(), GasPrice: tx.GasPrice().String(), Data: data, Sender: sender, CreatesContract: createsContract, RawData: toHex(tx.Data())} } func (self *Transaction) ToString() string { diff --git a/xeth/whisper.go b/xeth/whisper.go index f5c26faae..76bf8012a 100644 --- a/xeth/whisper.go +++ b/xeth/whisper.go @@ -5,7 +5,7 @@ import ( "time" "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/whisper" ) @@ -29,12 +29,12 @@ func (self *Whisper) Post(payload string, to, from string, topics []string, prio ttl = 100 } - pk := crypto.ToECDSAPub(ethutil.FromHex(from)) + pk := crypto.ToECDSAPub(common.FromHex(from)) if key := self.Whisper.GetIdentity(pk); key != nil || len(from) == 0 { - msg := whisper.NewMessage(ethutil.FromHex(payload)) + msg := whisper.NewMessage(common.FromHex(payload)) envelope, err := msg.Seal(time.Duration(priority*100000), whisper.Opts{ Ttl: time.Duration(ttl) * time.Second, - To: crypto.ToECDSAPub(ethutil.FromHex(to)), + To: crypto.ToECDSAPub(common.FromHex(to)), From: key, Topics: whisper.TopicsFromString(topics...), }) @@ -60,13 +60,13 @@ func (self *Whisper) NewIdentity() string { } func (self *Whisper) HasIdentity(key string) bool { - return self.Whisper.HasIdentity(crypto.ToECDSAPub(ethutil.FromHex(key))) + return self.Whisper.HasIdentity(crypto.ToECDSAPub(common.FromHex(key))) } func (self *Whisper) Watch(opts *Options) int { filter := whisper.Filter{ - To: crypto.ToECDSAPub(ethutil.FromHex(opts.To)), - From: crypto.ToECDSAPub(ethutil.FromHex(opts.From)), + To: crypto.ToECDSAPub(common.FromHex(opts.To)), + From: crypto.ToECDSAPub(common.FromHex(opts.From)), Topics: whisper.TopicsFromString(opts.Topics...), } diff --git a/xeth/xeth.go b/xeth/xeth.go index cf500cd59..6c7a26c04 100644 --- a/xeth/xeth.go +++ b/xeth/xeth.go @@ -11,7 +11,7 @@ import ( "github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethutil" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/p2p" @@ -30,9 +30,9 @@ type Backend interface { PeerCount() int IsListening() bool Peers() []*p2p.Peer - BlockDb() ethutil.Database - StateDb() ethutil.Database - ExtraDb() ethutil.Database + BlockDb() common.Database + StateDb() common.Database + ExtraDb() common.Database EventMux() *event.TypeMux Whisper() *whisper.Whisper @@ -116,21 +116,21 @@ func (self *XEth) State() *State { return self.state } func (self *XEth) Whisper() *Whisper { return self.whisper } func (self *XEth) BlockByHash(strHash string) *Block { - hash := ethutil.FromHex(strHash) + hash := common.FromHex(strHash) block := self.chainManager.GetBlock(hash) return NewBlock(block) } func (self *XEth) EthBlockByHash(strHash string) *types.Block { - hash := ethutil.FromHex(strHash) + hash := common.FromHex(strHash) block := self.chainManager.GetBlock(hash) return block } func (self *XEth) EthTransactionByHash(hash string) *types.Transaction { - data, _ := self.eth.ExtraDb().Get(ethutil.FromHex(hash)) + data, _ := self.eth.ExtraDb().Get(common.FromHex(hash)) if len(data) != 0 { return types.NewTransactionFromBytes(data) } @@ -205,9 +205,9 @@ func (self *XEth) Coinbase() string { } func (self *XEth) NumberToHuman(balance string) string { - b := ethutil.Big(balance) + b := common.Big(balance) - return ethutil.CurrencyToString(b) + return common.CurrencyToString(b) } func (self *XEth) StorageAt(addr, storageAddr string) string { @@ -233,7 +233,7 @@ func (self *XEth) IsContract(address string) bool { } func (self *XEth) SecretToAddress(key string) string { - pair, err := crypto.NewKeyPairFromSec(ethutil.FromHex(key)) + pair, err := crypto.NewKeyPairFromSec(common.FromHex(key)) if err != nil { return "" } @@ -263,29 +263,29 @@ func (self *XEth) EachStorage(addr string) string { } func (self *XEth) ToAscii(str string) string { - padded := ethutil.RightPadBytes([]byte(str), 32) + padded := common.RightPadBytes([]byte(str), 32) return "0x" + toHex(padded) } func (self *XEth) FromAscii(str string) string { - if ethutil.IsHex(str) { + if common.IsHex(str) { str = str[2:] } - return string(bytes.Trim(ethutil.FromHex(str), "\x00")) + return string(bytes.Trim(common.FromHex(str), "\x00")) } func (self *XEth) FromNumber(str string) string { - if ethutil.IsHex(str) { + if common.IsHex(str) { str = str[2:] } - return ethutil.BigD(ethutil.FromHex(str)).String() + return common.BigD(common.FromHex(str)).String() } func (self *XEth) PushTx(encodedTx string) (string, error) { - tx := types.NewTransactionFromBytes(ethutil.FromHex(encodedTx)) + tx := types.NewTransactionFromBytes(common.FromHex(encodedTx)) err := self.eth.TxPool().Add(tx) if err != nil { return "", err @@ -306,12 +306,12 @@ var ( func (self *XEth) Call(fromStr, toStr, valueStr, gasStr, gasPriceStr, dataStr string) (string, error) { statedb := self.State().State() //self.chainManager.TransState() msg := callmsg{ - from: statedb.GetOrNewStateObject(ethutil.FromHex(fromStr)), - to: ethutil.FromHex(toStr), - gas: ethutil.Big(gasStr), - gasPrice: ethutil.Big(gasPriceStr), - value: ethutil.Big(valueStr), - data: ethutil.FromHex(dataStr), + from: statedb.GetOrNewStateObject(common.FromHex(fromStr)), + to: common.FromHex(toStr), + gas: common.Big(gasStr), + gasPrice: common.Big(gasPriceStr), + value: common.Big(valueStr), + data: common.FromHex(dataStr), } if msg.gas.Cmp(big.NewInt(0)) == 0 { msg.gas = defaultGas @@ -332,16 +332,16 @@ func (self *XEth) Transact(fromStr, toStr, valueStr, gasStr, gasPriceStr, codeSt var ( from []byte to []byte - value = ethutil.NewValue(valueStr) - gas = ethutil.NewValue(gasStr) - price = ethutil.NewValue(gasPriceStr) + value = common.NewValue(valueStr) + gas = common.NewValue(gasStr) + price = common.NewValue(gasPriceStr) data []byte contractCreation bool ) - from = ethutil.FromHex(fromStr) - data = ethutil.FromHex(codeStr) - to = ethutil.FromHex(toStr) + from = common.FromHex(fromStr) + data = common.FromHex(codeStr) + to = common.FromHex(toStr) if len(to) == 0 { contractCreation = true } -- cgit v1.2.3