aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--cmd/evm/main.go4
-rw-r--r--cmd/geth/js.go17
-rw-r--r--cmd/geth/main.go6
-rw-r--r--cmd/utils/cmd.go13
-rw-r--r--cmd/utils/flags.go35
-rw-r--r--core/execution.go9
-rw-r--r--core/genesis.go24
-rw-r--r--core/state/statedb.go5
-rw-r--r--core/vm/environment.go2
-rw-r--r--core/vm/jit_test.go4
-rw-r--r--core/vm/vm.go7
-rw-r--r--core/vm_env.go4
-rw-r--r--crypto/crypto.go15
-rw-r--r--crypto/crypto_test.go181
-rw-r--r--eth/backend.go18
-rw-r--r--tests/util.go6
16 files changed, 272 insertions, 78 deletions
diff --git a/cmd/evm/main.go b/cmd/evm/main.go
index bf24da982..e170dc190 100644
--- a/cmd/evm/main.go
+++ b/cmd/evm/main.go
@@ -217,8 +217,8 @@ func (self *VMEnv) AddLog(log *vm.Log) {
func (self *VMEnv) CanTransfer(from common.Address, balance *big.Int) bool {
return self.state.GetBalance(from).Cmp(balance) >= 0
}
-func (self *VMEnv) Transfer(from, to vm.Account, amount *big.Int) error {
- return core.Transfer(from, to, amount)
+func (self *VMEnv) Transfer(from, to vm.Account, amount *big.Int) {
+ core.Transfer(from, to, amount)
}
func (self *VMEnv) Call(caller vm.ContractRef, addr common.Address, data []byte, gas, price, value *big.Int) ([]byte, error) {
diff --git a/cmd/geth/js.go b/cmd/geth/js.go
index 3e3600705..b5ec82b57 100644
--- a/cmd/geth/js.go
+++ b/cmd/geth/js.go
@@ -145,7 +145,7 @@ func apiWordCompleter(line string, pos int) (head string, completions []string,
return begin, completionWords, end
}
-func newLightweightJSRE(libPath string, client comms.EthereumClient, interactive bool) *jsre {
+func newLightweightJSRE(libPath string, client comms.EthereumClient, datadir string, interactive bool) *jsre {
js := &jsre{ps1: "> "}
js.wait = make(chan *big.Int)
js.client = client
@@ -161,14 +161,14 @@ func newLightweightJSRE(libPath string, client comms.EthereumClient, interactive
js.prompter = dumbterm{bufio.NewReader(os.Stdin)}
} else {
lr := liner.NewLiner()
- js.withHistory(func(hist *os.File) { lr.ReadHistory(hist) })
+ js.withHistory(datadir, func(hist *os.File) { lr.ReadHistory(hist) })
lr.SetCtrlCAborts(true)
js.loadAutoCompletion()
lr.SetWordCompleter(apiWordCompleter)
lr.SetTabCompletionStyle(liner.TabPrints)
js.prompter = lr
js.atexit = func() {
- js.withHistory(func(hist *os.File) { hist.Truncate(0); lr.WriteHistory(hist) })
+ js.withHistory(datadir, func(hist *os.File) { hist.Truncate(0); lr.WriteHistory(hist) })
lr.Close()
close(js.wait)
}
@@ -203,14 +203,14 @@ func newJSRE(ethereum *eth.Ethereum, libPath, corsDomain string, client comms.Et
js.prompter = dumbterm{bufio.NewReader(os.Stdin)}
} else {
lr := liner.NewLiner()
- js.withHistory(func(hist *os.File) { lr.ReadHistory(hist) })
+ js.withHistory(ethereum.DataDir, func(hist *os.File) { lr.ReadHistory(hist) })
lr.SetCtrlCAborts(true)
js.loadAutoCompletion()
lr.SetWordCompleter(apiWordCompleter)
lr.SetTabCompletionStyle(liner.TabPrints)
js.prompter = lr
js.atexit = func() {
- js.withHistory(func(hist *os.File) { hist.Truncate(0); lr.WriteHistory(hist) })
+ js.withHistory(ethereum.DataDir, func(hist *os.File) { hist.Truncate(0); lr.WriteHistory(hist) })
lr.Close()
close(js.wait)
}
@@ -433,12 +433,7 @@ func hidepassword(input string) string {
}
}
-func (self *jsre) withHistory(op func(*os.File)) {
- datadir := common.DefaultDataDir()
- if self.ethereum != nil {
- datadir = self.ethereum.DataDir
- }
-
+func (self *jsre) withHistory(datadir string, op func(*os.File)) {
hist, err := os.OpenFile(filepath.Join(datadir, "history"), os.O_RDWR|os.O_CREATE, os.ModePerm)
if err != nil {
fmt.Printf("unable to open history file: %v\n", err)
diff --git a/cmd/geth/main.go b/cmd/geth/main.go
index fa9beafd0..1eb078201 100644
--- a/cmd/geth/main.go
+++ b/cmd/geth/main.go
@@ -314,6 +314,7 @@ JavaScript API. See https://github.com/ethereum/go-ethereum/wiki/Javascipt-Conso
utils.ExecFlag,
utils.WhisperEnabledFlag,
utils.DevModeFlag,
+ utils.TestNetFlag,
utils.VMDebugFlag,
utils.VMForceJitFlag,
utils.VMJitCacheFlag,
@@ -340,6 +341,7 @@ JavaScript API. See https://github.com/ethereum/go-ethereum/wiki/Javascipt-Conso
}
app.Before = func(ctx *cli.Context) error {
utils.SetupLogger(ctx)
+ utils.SetupNetwork(ctx)
utils.SetupVM(ctx)
utils.SetupEth(ctx)
if ctx.GlobalBool(utils.PProfEanbledFlag.Name) {
@@ -391,9 +393,6 @@ func makeDefaultExtra() []byte {
func run(ctx *cli.Context) {
utils.CheckLegalese(utils.MustDataDir(ctx))
- if ctx.GlobalBool(utils.OlympicFlag.Name) {
- utils.InitOlympic()
- }
cfg := utils.MakeEthConfig(ClientIdentifier, nodeNameVersion, ctx)
cfg.ExtraData = makeExtra(ctx)
@@ -429,6 +428,7 @@ func attach(ctx *cli.Context) {
repl := newLightweightJSRE(
ctx.GlobalString(utils.JSpathFlag.Name),
client,
+ ctx.GlobalString(utils.DataDirFlag.Name),
true,
)
diff --git a/cmd/utils/cmd.go b/cmd/utils/cmd.go
index 5e4bfc937..1fbd96dc8 100644
--- a/cmd/utils/cmd.go
+++ b/cmd/utils/cmd.go
@@ -21,8 +21,6 @@ import (
"bufio"
"fmt"
"io"
- "math"
- "math/big"
"os"
"os/signal"
"regexp"
@@ -34,7 +32,6 @@ import (
"github.com/ethereum/go-ethereum/eth"
"github.com/ethereum/go-ethereum/logger"
"github.com/ethereum/go-ethereum/logger/glog"
- "github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/rlp"
"github.com/peterh/liner"
)
@@ -146,16 +143,6 @@ func StartEthereum(ethereum *eth.Ethereum) {
}()
}
-func InitOlympic() {
- params.DurationLimit = big.NewInt(8)
- params.GenesisGasLimit = big.NewInt(3141592)
- params.MinGasLimit = big.NewInt(125000)
- params.MaximumExtraDataSize = big.NewInt(1024)
- NetworkIdFlag.Value = 0
- core.BlockReward = big.NewInt(1.5e+18)
- core.ExpDiffPeriod = big.NewInt(math.MaxInt64)
-}
-
func FormatTransactionData(data string) []byte {
d := common.StringToByteFunc(data, func(s string) (ret []byte) {
slice := regexp.MustCompile("\\n|\\s").Split(s, 1000000000)
diff --git a/cmd/utils/flags.go b/cmd/utils/flags.go
index dea43bc5c..53faeefdc 100644
--- a/cmd/utils/flags.go
+++ b/cmd/utils/flags.go
@@ -20,6 +20,7 @@ import (
"crypto/ecdsa"
"fmt"
"log"
+ "math"
"math/big"
"net"
"net/http"
@@ -42,6 +43,7 @@ import (
"github.com/ethereum/go-ethereum/logger/glog"
"github.com/ethereum/go-ethereum/metrics"
"github.com/ethereum/go-ethereum/p2p/nat"
+ "github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/rpc/api"
"github.com/ethereum/go-ethereum/rpc/codec"
"github.com/ethereum/go-ethereum/rpc/comms"
@@ -125,6 +127,10 @@ var (
Name: "dev",
Usage: "Developer mode. This mode creates a private network and sets several debugging flags",
}
+ TestNetFlag = cli.BoolFlag{
+ Name: "testnet",
+ Usage: "Testnet mode. This enables your node to operate on the testnet",
+ }
IdentityFlag = cli.StringFlag{
Name: "identity",
Usage: "Custom node name",
@@ -452,6 +458,17 @@ func MakeEthConfig(clientID, version string, ctx *cli.Context) *eth.Config {
AutoDAG: ctx.GlobalBool(AutoDAGFlag.Name) || ctx.GlobalBool(MiningEnabledFlag.Name),
}
+ if ctx.GlobalBool(DevModeFlag.Name) && ctx.GlobalBool(TestNetFlag.Name) {
+ glog.Fatalf("%s and %s are mutually exclusive\n", DevModeFlag.Name, TestNetFlag.Name)
+ }
+
+ if ctx.GlobalBool(TestNetFlag.Name) {
+ // testnet is always stored in the testnet folder
+ cfg.DataDir += "/testnet"
+ cfg.NetworkId = 2
+ cfg.TestNet = true
+ }
+
if ctx.GlobalBool(DevModeFlag.Name) {
if !ctx.GlobalIsSet(VMDebugFlag.Name) {
cfg.VmDebug = true
@@ -488,6 +505,20 @@ func SetupLogger(ctx *cli.Context) {
glog.SetLogDir(ctx.GlobalString(LogFileFlag.Name))
}
+// SetupNetwork configures the system for either the main net or some test network.
+func SetupNetwork(ctx *cli.Context) {
+ switch {
+ case ctx.GlobalBool(OlympicFlag.Name):
+ params.DurationLimit = big.NewInt(8)
+ params.GenesisGasLimit = big.NewInt(3141592)
+ params.MinGasLimit = big.NewInt(125000)
+ params.MaximumExtraDataSize = big.NewInt(1024)
+ NetworkIdFlag.Value = 0
+ core.BlockReward = big.NewInt(1.5e+18)
+ core.ExpDiffPeriod = big.NewInt(math.MaxInt64)
+ }
+}
+
// SetupVM configured the VM package's global settings
func SetupVM(ctx *cli.Context) {
vm.EnableJit = ctx.GlobalBool(VMEnableJitFlag.Name)
@@ -517,7 +548,6 @@ func MakeChain(ctx *cli.Context) (chain *core.BlockChain, chainDb ethdb.Database
Fatalf("Could not open database: %v", err)
}
if ctx.GlobalBool(OlympicFlag.Name) {
- InitOlympic()
_, err := core.WriteTestNetGenesisBlock(chainDb, 42)
if err != nil {
glog.Fatalln(err)
@@ -540,6 +570,9 @@ func MakeChain(ctx *cli.Context) (chain *core.BlockChain, chainDb ethdb.Database
// MakeChain creates an account manager from set command line flags.
func MakeAccountManager(ctx *cli.Context) *accounts.Manager {
dataDir := MustDataDir(ctx)
+ if ctx.GlobalBool(TestNetFlag.Name) {
+ dataDir += "/testnet"
+ }
ks := crypto.NewKeyStorePassphrase(filepath.Join(dataDir, "keystore"))
return accounts.NewManager(ks)
}
diff --git a/core/execution.go b/core/execution.go
index e3c00a2ea..fd8464f6e 100644
--- a/core/execution.go
+++ b/core/execution.go
@@ -17,7 +17,6 @@
package core
import (
- "errors"
"math/big"
"github.com/ethereum/go-ethereum/common"
@@ -108,13 +107,7 @@ func exec(env vm.Environment, caller vm.ContractRef, address, codeAddr *common.A
}
// generic transfer method
-func Transfer(from, to vm.Account, amount *big.Int) error {
- if from.Balance().Cmp(amount) < 0 {
- return errors.New("Insufficient balance in account")
- }
-
+func Transfer(from, to vm.Account, amount *big.Int) {
from.SubBalance(amount)
to.AddBalance(amount)
-
- return nil
}
diff --git a/core/genesis.go b/core/genesis.go
index bf97da2e2..4c5c17f60 100644
--- a/core/genesis.go
+++ b/core/genesis.go
@@ -102,6 +102,9 @@ func WriteGenesisBlock(chainDb ethdb.Database, reader io.Reader) (*types.Block,
if err := WriteBlock(chainDb, block); err != nil {
return nil, err
}
+ if err := PutBlockReceipts(chainDb, block, nil); err != nil {
+ return nil, err
+ }
if err := WriteCanonicalHash(chainDb, block.Hash(), block.NumberU64()); err != nil {
return nil, err
}
@@ -156,6 +159,27 @@ func WriteGenesisBlockForTesting(db ethdb.Database, accounts ...GenesisAccount)
func WriteTestNetGenesisBlock(chainDb ethdb.Database, nonce uint64) (*types.Block, error) {
testGenesis := fmt.Sprintf(`{
+ "nonce": "0x%x",
+ "difficulty": "0x20000",
+ "mixhash": "0x00000000000000000000000000000000000000647572616c65787365646c6578",
+ "coinbase": "0x0000000000000000000000000000000000000000",
+ "timestamp": "0x00",
+ "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
+ "extraData": "0x",
+ "gasLimit": "0x2FEFD8",
+ "alloc": {
+ "0000000000000000000000000000000000000001": { "balance": "1" },
+ "0000000000000000000000000000000000000002": { "balance": "1" },
+ "0000000000000000000000000000000000000003": { "balance": "1" },
+ "0000000000000000000000000000000000000004": { "balance": "1" },
+ "102e61f5d8f9bc71d0ad4a084df4e65e05ce0e1c": { "balance": "1606938044258990275541962092341162602522202993782792835301376" }
+ }
+}`, types.EncodeNonce(nonce))
+ return WriteGenesisBlock(chainDb, strings.NewReader(testGenesis))
+}
+
+func WriteOlympicGenesisBlock(chainDb ethdb.Database, nonce uint64) (*types.Block, error) {
+ testGenesis := fmt.Sprintf(`{
"nonce":"0x%x",
"gasLimit":"0x%x",
"difficulty":"0x%x",
diff --git a/core/state/statedb.go b/core/state/statedb.go
index 499ea5f52..ad673aecb 100644
--- a/core/state/statedb.go
+++ b/core/state/statedb.go
@@ -28,6 +28,10 @@ import (
"github.com/ethereum/go-ethereum/trie"
)
+// The starting nonce determines the default nonce when new accounts are being
+// created.
+var StartingNonce uint64
+
// StateDBs within the ethereum protocol are used to store anything
// within the merkle trie. StateDBs take care of caching and storing
// nested states. It's the general query interface to retrieve:
@@ -263,6 +267,7 @@ func (self *StateDB) newStateObject(addr common.Address) *StateObject {
}
stateObject := NewStateObject(addr, self.db)
+ stateObject.SetNonce(StartingNonce)
self.stateObjects[addr.Str()] = stateObject
return stateObject
diff --git a/core/vm/environment.go b/core/vm/environment.go
index f8e19baea..ec739b26c 100644
--- a/core/vm/environment.go
+++ b/core/vm/environment.go
@@ -51,7 +51,7 @@ type Environment interface {
// Determines whether it's possible to transact
CanTransfer(from common.Address, balance *big.Int) bool
// Transfers amount from one account to the other
- Transfer(from, to Account, amount *big.Int) error
+ Transfer(from, to Account, amount *big.Int)
// Adds a LOG to the state
AddLog(*Log)
// Adds a structured log to the env
diff --git a/core/vm/jit_test.go b/core/vm/jit_test.go
index 8c45f2ce7..cb09e179d 100644
--- a/core/vm/jit_test.go
+++ b/core/vm/jit_test.go
@@ -152,9 +152,7 @@ func (self *Env) SetDepth(i int) { self.depth = i }
func (self *Env) CanTransfer(from common.Address, balance *big.Int) bool {
return true
}
-func (self *Env) Transfer(from, to Account, amount *big.Int) error {
- return nil
-}
+func (self *Env) Transfer(from, to Account, amount *big.Int) {}
func (self *Env) Call(caller ContractRef, addr common.Address, data []byte, gas, price, value *big.Int) ([]byte, error) {
return nil, nil
}
diff --git a/core/vm/vm.go b/core/vm/vm.go
index 57dd4dac3..4b03e55f0 100644
--- a/core/vm/vm.go
+++ b/core/vm/vm.go
@@ -370,9 +370,11 @@ func (self *Vm) log(pc uint64, op OpCode, gas, cost *big.Int, memory *Memory, st
if Debug {
mem := make([]byte, len(memory.Data()))
copy(mem, memory.Data())
- stck := make([]*big.Int, len(stack.Data()))
- copy(stck, stack.Data())
+ stck := make([]*big.Int, len(stack.Data()))
+ for i, item := range stack.Data() {
+ stck[i] = new(big.Int).Set(item)
+ }
storage := make(map[common.Hash][]byte)
/*
object := contract.self.(*state.StateObject)
@@ -380,7 +382,6 @@ func (self *Vm) log(pc uint64, op OpCode, gas, cost *big.Int, memory *Memory, st
storage[common.BytesToHash(k)] = v
})
*/
-
self.env.AddStructLog(StructLog{pc, op, new(big.Int).Set(gas), cost, mem, stck, storage, err})
}
}
diff --git a/core/vm_env.go b/core/vm_env.go
index 467e34c6b..715fde52f 100644
--- a/core/vm_env.go
+++ b/core/vm_env.go
@@ -81,8 +81,8 @@ func (self *VMEnv) SetSnapshot(copy vm.Database) {
self.state.Set(copy.(*state.StateDB))
}
-func (self *VMEnv) Transfer(from, to vm.Account, amount *big.Int) error {
- return Transfer(from, to, amount)
+func (self *VMEnv) Transfer(from, to vm.Account, amount *big.Int) {
+ Transfer(from, to, amount)
}
func (self *VMEnv) Call(me vm.ContractRef, addr common.Address, data []byte, gas, price, value *big.Int) ([]byte, error) {
diff --git a/crypto/crypto.go b/crypto/crypto.go
index b3a8d730b..272050106 100644
--- a/crypto/crypto.go
+++ b/crypto/crypto.go
@@ -172,10 +172,10 @@ func GenerateKey() (*ecdsa.PrivateKey, error) {
}
func ValidateSignatureValues(v byte, r, s *big.Int) bool {
- vint := uint32(v)
- if r.Cmp(common.Big0) == 0 || s.Cmp(common.Big0) == 0 {
+ if r.Cmp(common.Big1) < 0 || s.Cmp(common.Big1) < 0 {
return false
}
+ vint := uint32(v)
if r.Cmp(secp256k1n) < 0 && s.Cmp(secp256k1n) < 0 && (vint == 27 || vint == 28) {
return true
} else {
@@ -302,17 +302,6 @@ func aesCBCDecrypt(key, cipherText, iv []byte) ([]byte, error) {
}
// From https://leanpub.com/gocrypto/read#leanpub-auto-block-cipher-modes
-func PKCS7Pad(in []byte) []byte {
- padding := 16 - (len(in) % 16)
- if padding == 0 {
- padding = 16
- }
- for i := 0; i < padding; i++ {
- in = append(in, byte(padding))
- }
- return in
-}
-
func PKCS7Unpad(in []byte) []byte {
if len(in) == 0 {
return nil
diff --git a/crypto/crypto_test.go b/crypto/crypto_test.go
index b891f41a9..fdd9c1ee8 100644
--- a/crypto/crypto_test.go
+++ b/crypto/crypto_test.go
@@ -18,8 +18,12 @@ package crypto
import (
"bytes"
+ "crypto/ecdsa"
"encoding/hex"
"fmt"
+ "io/ioutil"
+ "math/big"
+ "os"
"testing"
"time"
@@ -27,10 +31,12 @@ import (
"github.com/ethereum/go-ethereum/crypto/secp256k1"
)
+var testAddrHex = "970e8128ab834e8eac17ab8e3812f010678cf791"
+var testPrivHex = "289c2857d4598e37fb9647507e47a309d6133539bf21a8b9cb6df88fd5232032"
+
// These tests are sanity checks.
// They should ensure that we don't e.g. use Sha3-224 instead of Sha3-256
// and that the sha3 library uses keccak-f permutation.
-
func TestSha3(t *testing.T) {
msg := []byte("abc")
exp, _ := hex.DecodeString("4e03657aea45a94fc7d47ba826c8d667c0d1e6e33a64a036ec44f58fa12d6c45")
@@ -55,13 +61,6 @@ func TestRipemd160(t *testing.T) {
checkhash(t, "Ripemd160", Ripemd160, msg, exp)
}
-func checkhash(t *testing.T, name string, f func([]byte) []byte, msg, exp []byte) {
- sum := f(msg)
- if bytes.Compare(exp, sum) != 0 {
- t.Errorf("hash %s returned wrong result.\ngot: %x\nwant: %x", name, sum, exp)
- }
-}
-
func BenchmarkSha3(b *testing.B) {
a := []byte("hello world")
amount := 1000000
@@ -74,13 +73,41 @@ func BenchmarkSha3(b *testing.B) {
}
func Test0Key(t *testing.T) {
- t.Skip()
- key := common.Hex2Bytes("1111111111111111111111111111111111111111111111111111111111111111")
+ key := common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000000")
+ _, err := secp256k1.GeneratePubKey(key)
+ if err == nil {
+ t.Errorf("expected error due to zero privkey")
+ }
+}
+
+func TestSign(t *testing.T) {
+ key, _ := HexToECDSA(testPrivHex)
+ addr := common.HexToAddress(testAddrHex)
+
+ msg := Sha3([]byte("foo"))
+ sig, err := Sign(msg, key)
+ if err != nil {
+ t.Errorf("Sign error: %s", err)
+ }
+ recoveredPub, err := Ecrecover(msg, sig)
+ if err != nil {
+ t.Errorf("ECRecover error: %s", err)
+ }
+ recoveredAddr := PubkeyToAddress(*ToECDSAPub(recoveredPub))
+ if addr != recoveredAddr {
+ t.Errorf("Address mismatch: want: %x have: %x", addr, recoveredAddr)
+ }
+
+ // should be equal to SigToPub
+ recoveredPub2, err := SigToPub(msg, sig)
+ if err != nil {
+ t.Errorf("ECRecover error: %s", err)
+ }
+ recoveredAddr2 := PubkeyToAddress(*recoveredPub2)
+ if addr != recoveredAddr2 {
+ t.Errorf("Address mismatch: want: %x have: %x", addr, recoveredAddr2)
+ }
- p, err := secp256k1.GeneratePubKey(key)
- addr := Sha3(p[1:])[12:]
- fmt.Printf("%x\n", p)
- fmt.Printf("%v %x\n", err, addr)
}
func TestInvalidSign(t *testing.T) {
@@ -94,3 +121,129 @@ func TestInvalidSign(t *testing.T) {
t.Errorf("expected sign with hash 33 byte to error")
}
}
+
+func TestNewContractAddress(t *testing.T) {
+ key, _ := HexToECDSA(testPrivHex)
+ addr := common.HexToAddress(testAddrHex)
+ genAddr := PubkeyToAddress(key.PublicKey)
+ // sanity check before using addr to create contract address
+ checkAddr(t, genAddr, addr)
+
+ caddr0 := CreateAddress(addr, 0)
+ caddr1 := CreateAddress(addr, 1)
+ caddr2 := CreateAddress(addr, 2)
+ checkAddr(t, common.HexToAddress("333c3310824b7c685133f2bedb2ca4b8b4df633d"), caddr0)
+ checkAddr(t, common.HexToAddress("8bda78331c916a08481428e4b07c96d3e916d165"), caddr1)
+ checkAddr(t, common.HexToAddress("c9ddedf451bc62ce88bf9292afb13df35b670699"), caddr2)
+}
+
+func TestLoadECDSAFile(t *testing.T) {
+ keyBytes := common.FromHex(testPrivHex)
+ fileName0 := "test_key0"
+ fileName1 := "test_key1"
+ checkKey := func(k *ecdsa.PrivateKey) {
+ checkAddr(t, PubkeyToAddress(k.PublicKey), common.HexToAddress(testAddrHex))
+ loadedKeyBytes := FromECDSA(k)
+ if !bytes.Equal(loadedKeyBytes, keyBytes) {
+ t.Fatalf("private key mismatch: want: %x have: %x", keyBytes, loadedKeyBytes)
+ }
+ }
+
+ ioutil.WriteFile(fileName0, []byte(testPrivHex), 0600)
+ defer os.Remove(fileName0)
+
+ key0, err := LoadECDSA(fileName0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ checkKey(key0)
+
+ // again, this time with SaveECDSA instead of manual save:
+ err = SaveECDSA(fileName1, key0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer os.Remove(fileName1)
+
+ key1, err := LoadECDSA(fileName1)
+ if err != nil {
+ t.Fatal(err)
+ }
+ checkKey(key1)
+}
+
+func TestValidateSignatureValues(t *testing.T) {
+ check := func(expected bool, v byte, r, s *big.Int) {
+ if ValidateSignatureValues(v, r, s) != expected {
+ t.Errorf("mismatch for v: %d r: %d s: %d want: %v", v, r, s, expected)
+ }
+ }
+ minusOne := big.NewInt(-1)
+ one := common.Big1
+ zero := common.Big0
+ secp256k1nMinus1 := new(big.Int).Sub(secp256k1n, common.Big1)
+
+ // correct v,r,s
+ check(true, 27, one, one)
+ check(true, 28, one, one)
+ // incorrect v, correct r,s,
+ check(false, 30, one, one)
+ check(false, 26, one, one)
+
+ // incorrect v, combinations of incorrect/correct r,s at lower limit
+ check(false, 0, zero, zero)
+ check(false, 0, zero, one)
+ check(false, 0, one, zero)
+ check(false, 0, one, one)
+
+ // correct v for any combination of incorrect r,s
+ check(false, 27, zero, zero)
+ check(false, 27, zero, one)
+ check(false, 27, one, zero)
+
+ check(false, 28, zero, zero)
+ check(false, 28, zero, one)
+ check(false, 28, one, zero)
+
+ // correct sig with max r,s
+ check(true, 27, secp256k1nMinus1, secp256k1nMinus1)
+ // correct v, combinations of incorrect r,s at upper limit
+ check(false, 27, secp256k1n, secp256k1nMinus1)
+ check(false, 27, secp256k1nMinus1, secp256k1n)
+ check(false, 27, secp256k1n, secp256k1n)
+
+ // current callers ensures r,s cannot be negative, but let's test for that too
+ // as crypto package could be used stand-alone
+ check(false, 27, minusOne, one)
+ check(false, 27, one, minusOne)
+}
+
+func checkhash(t *testing.T, name string, f func([]byte) []byte, msg, exp []byte) {
+ sum := f(msg)
+ if bytes.Compare(exp, sum) != 0 {
+ t.Fatalf("hash %s mismatch: want: %x have: %x", name, exp, sum)
+ }
+}
+
+func checkAddr(t *testing.T, addr0, addr1 common.Address) {
+ if addr0 != addr1 {
+ t.Fatalf("address mismatch: want: %x have: %x", addr0, addr1)
+ }
+}
+
+// test to help Python team with integration of libsecp256k1
+// skip but keep it after they are done
+func TestPythonIntegration(t *testing.T) {
+ kh := "289c2857d4598e37fb9647507e47a309d6133539bf21a8b9cb6df88fd5232032"
+ k0, _ := HexToECDSA(kh)
+ k1 := FromECDSA(k0)
+
+ msg0 := Sha3([]byte("foo"))
+ sig0, _ := secp256k1.Sign(msg0, k1)
+
+ msg1 := common.FromHex("00000000000000000000000000000000")
+ sig1, _ := secp256k1.Sign(msg0, k1)
+
+ fmt.Printf("msg: %x, privkey: %x sig: %x\n", msg0, k1, sig0)
+ fmt.Printf("msg: %x, privkey: %x sig: %x\n", msg1, k1, sig1)
+}
diff --git a/eth/backend.go b/eth/backend.go
index a480b4931..83eefca5b 100644
--- a/eth/backend.go
+++ b/eth/backend.go
@@ -34,6 +34,7 @@ import (
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/compiler"
"github.com/ethereum/go-ethereum/core"
+ "github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/crypto"
@@ -69,12 +70,17 @@ var (
discover.MustParseNode("enode://979b7fa28feeb35a4741660a16076f1943202cb72b6af70d327f053e248bab9ba81760f39d0701ef1d8f89cc1fbd2cacba0710a12cd5314d5e0c9021aa3637f9@5.1.83.226:30303"),
}
+ defaultTestNetBootNodes = []*discover.Node{
+ discover.MustParseNode("enode://5374c1bff8df923d3706357eeb4983cd29a63be40a269aaa2296ee5f3b2119a8978c0ed68b8f6fc84aad0df18790417daadf91a4bfbb786a16c9b0a199fa254a@92.51.165.126:30303"),
+ }
+
staticNodes = "static-nodes.json" // Path within <datadir> to search for the static node list
trustedNodes = "trusted-nodes.json" // Path within <datadir> to search for the trusted node list
)
type Config struct {
DevMode bool
+ TestNet bool
Name string
NetworkId int
@@ -133,6 +139,10 @@ type Config struct {
func (cfg *Config) parseBootNodes() []*discover.Node {
if cfg.BootNodes == "" {
+ if cfg.TestNet {
+ return defaultTestNetBootNodes
+ }
+
return defaultBootNodes
}
var ns []*discover.Node
@@ -309,7 +319,13 @@ func New(config *Config) (*Ethereum, error) {
glog.V(logger.Error).Infoln("Starting Olympic network")
fallthrough
case config.DevMode:
- _, err := core.WriteTestNetGenesisBlock(chainDb, 42)
+ _, err := core.WriteOlympicGenesisBlock(chainDb, 42)
+ if err != nil {
+ return nil, err
+ }
+ case config.TestNet:
+ state.StartingNonce = 1048576 // (2**20)
+ _, err := core.WriteTestNetGenesisBlock(chainDb, 0x6d6f7264656e)
if err != nil {
return nil, err
}
diff --git a/tests/util.go b/tests/util.go
index fb9e518c8..bbc671169 100644
--- a/tests/util.go
+++ b/tests/util.go
@@ -209,11 +209,11 @@ func (self *Env) SetSnapshot(copy vm.Database) {
self.state.Set(copy.(*state.StateDB))
}
-func (self *Env) Transfer(from, to vm.Account, amount *big.Int) error {
+func (self *Env) Transfer(from, to vm.Account, amount *big.Int) {
if self.skipTransfer {
- return nil
+ return
}
- return core.Transfer(from, to, amount)
+ core.Transfer(from, to, amount)
}
func (self *Env) Call(caller vm.ContractRef, addr common.Address, data []byte, gas, price, value *big.Int) ([]byte, error) {