From 1f2547b8a7cfe100f64428d20f4bcf95eb9ecc5c Mon Sep 17 00:00:00 2001 From: obscuren Date: Sat, 22 Mar 2014 01:02:24 +0100 Subject: Major re-organisation. The Ethereum node and Gui are now separated. --- utils/keys.go | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 utils/keys.go (limited to 'utils') diff --git a/utils/keys.go b/utils/keys.go new file mode 100644 index 000000000..910c8c477 --- /dev/null +++ b/utils/keys.go @@ -0,0 +1,50 @@ +package utils + +import ( + "fmt" + "github.com/ethereum/eth-go/ethutil" + "github.com/obscuren/secp256k1-go" +) + +func CreateKeyPair(force bool) { + data, _ := ethutil.Config.Db.Get([]byte("KeyRing")) + if len(data) == 0 || force { + pub, prv := secp256k1.GenerateKeyPair() + pair := ðutil.Key{PrivateKey: prv, PublicKey: pub} + ethutil.Config.Db.Put([]byte("KeyRing"), pair.RlpEncode()) + + fmt.Printf(` +Generating new address and keypair. +Please keep your keys somewhere save. + +++++++++++++++++ KeyRing +++++++++++++++++++ +addr: %x +prvk: %x +pubk: %x +++++++++++++++++++++++++++++++++++++++++++++ + +`, pair.Address(), prv, pub) + + } +} + +func ImportPrivateKey(prvKey string) { + key := ethutil.FromHex(prvKey) + msg := []byte("tmp") + // Couldn't think of a better way to get the pub key + sig, _ := secp256k1.Sign(msg, key) + pub, _ := secp256k1.RecoverPubkey(msg, sig) + pair := ðutil.Key{PrivateKey: key, PublicKey: pub} + ethutil.Config.Db.Put([]byte("KeyRing"), pair.RlpEncode()) + + fmt.Printf(` +Importing private key + +++++++++++++++++ KeyRing +++++++++++++++++++ +addr: %x +prvk: %x +pubk: %x +++++++++++++++++++++++++++++++++++++++++++++ + +`, pair.Address(), key, pub) +} -- cgit v1.2.3 From 2edf133b4671287e58c1f8cdb22f0cd342f309f2 Mon Sep 17 00:00:00 2001 From: Maran Date: Mon, 7 Apr 2014 13:59:42 +0200 Subject: Added mnemonic priv key --- utils/keys.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'utils') diff --git a/utils/keys.go b/utils/keys.go index 910c8c477..2f39c10b2 100644 --- a/utils/keys.go +++ b/utils/keys.go @@ -12,6 +12,7 @@ func CreateKeyPair(force bool) { pub, prv := secp256k1.GenerateKeyPair() pair := ðutil.Key{PrivateKey: prv, PublicKey: pub} ethutil.Config.Db.Put([]byte("KeyRing"), pair.RlpEncode()) + mne := ethutil.MnemonicEncode(ethutil.Hex(prv)) fmt.Printf(` Generating new address and keypair. @@ -22,8 +23,8 @@ addr: %x prvk: %x pubk: %x ++++++++++++++++++++++++++++++++++++++++++++ - -`, pair.Address(), prv, pub) +save these words so you can restore your account later: %s +`, pair.Address(), prv, pub, mne) } } -- cgit v1.2.3 From 9cf77cdbadd8249498d62542502def6ecb2fb6b8 Mon Sep 17 00:00:00 2001 From: obscuren Date: Wed, 16 Apr 2014 04:08:37 +0200 Subject: Moved compiling related object to utils package --- utils/compile.go | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 utils/compile.go (limited to 'utils') diff --git a/utils/compile.go b/utils/compile.go new file mode 100644 index 000000000..e5ea50ad4 --- /dev/null +++ b/utils/compile.go @@ -0,0 +1,24 @@ +package utils + +import ( + "fmt" + "github.com/ethereum/eth-go/ethutil" + "github.com/obscuren/mutan" + "strings" +) + +// General compile function +func Compile(script string) ([]byte, error) { + asm, errors := mutan.Compile(strings.NewReader(script), false) + if len(errors) > 0 { + var errs string + for _, er := range errors { + if er != nil { + errs += er.Error() + } + } + return nil, fmt.Errorf("%v", errs) + } + + return ethutil.Assemble(asm...), nil +} -- cgit v1.2.3 From 43f1214f97e52863b1f1ef7913991bef3d00c58e Mon Sep 17 00:00:00 2001 From: obscuren Date: Wed, 23 Apr 2014 15:54:34 +0200 Subject: Refactored code --- utils/compile.go | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) (limited to 'utils') diff --git a/utils/compile.go b/utils/compile.go index e5ea50ad4..894fc2d09 100644 --- a/utils/compile.go +++ b/utils/compile.go @@ -22,3 +22,21 @@ func Compile(script string) ([]byte, error) { return ethutil.Assemble(asm...), nil } + +func CompileScript(script string) ([]byte, []byte, error) { + // Preprocess + mainInput, initInput := ethutil.PreProcess(script) + // Compile main script + mainScript, err := Compile(mainInput) + if err != nil { + return nil, nil, err + } + + // Compile init script + initScript, err := Compile(initInput) + if err != nil { + return nil, nil, err + } + + return mainScript, initScript, nil +} -- cgit v1.2.3 From 883810b53328b302aa765ccf9d228bd73c046cac Mon Sep 17 00:00:00 2001 From: obscuren Date: Sun, 27 Apr 2014 18:05:48 +0200 Subject: Using mutan assembler stage --- utils/compile.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'utils') diff --git a/utils/compile.go b/utils/compile.go index 894fc2d09..12e3a60c3 100644 --- a/utils/compile.go +++ b/utils/compile.go @@ -9,7 +9,7 @@ import ( // General compile function func Compile(script string) ([]byte, error) { - asm, errors := mutan.Compile(strings.NewReader(script), false) + byteCode, errors := mutan.Compile(strings.NewReader(script), false) if len(errors) > 0 { var errs string for _, er := range errors { @@ -20,7 +20,7 @@ func Compile(script string) ([]byte, error) { return nil, fmt.Errorf("%v", errs) } - return ethutil.Assemble(asm...), nil + return byteCode, nil } func CompileScript(script string) ([]byte, []byte, error) { -- cgit v1.2.3 From a0f35d324822fc66951f8a33526ff3d15b0de09d Mon Sep 17 00:00:00 2001 From: Casey Kuhlman Date: Mon, 28 Apr 2014 11:37:44 +0200 Subject: PreProcess moved to Mutan package --- utils/compile.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'utils') diff --git a/utils/compile.go b/utils/compile.go index 12e3a60c3..6d75f73d1 100644 --- a/utils/compile.go +++ b/utils/compile.go @@ -2,7 +2,6 @@ package utils import ( "fmt" - "github.com/ethereum/eth-go/ethutil" "github.com/obscuren/mutan" "strings" ) @@ -25,7 +24,7 @@ func Compile(script string) ([]byte, error) { func CompileScript(script string) ([]byte, []byte, error) { // Preprocess - mainInput, initInput := ethutil.PreProcess(script) + mainInput, initInput := mutan.PreProcess(script) // Compile main script mainScript, err := Compile(mainInput) if err != nil { -- cgit v1.2.3 From 471bd398f380bc26ba3144a0834092036565e429 Mon Sep 17 00:00:00 2001 From: obscuren Date: Fri, 2 May 2014 12:07:24 +0200 Subject: Moved Ext ethereum api Moved the external ethereum api which can be used by any 3rd party application. --- utils/ethereum.go | 107 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ utils/types.go | 83 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 190 insertions(+) create mode 100644 utils/ethereum.go create mode 100644 utils/types.go (limited to 'utils') diff --git a/utils/ethereum.go b/utils/ethereum.go new file mode 100644 index 000000000..c383c4c91 --- /dev/null +++ b/utils/ethereum.go @@ -0,0 +1,107 @@ +package utils + +import ( + "github.com/ethereum/eth-go" + "github.com/ethereum/eth-go/ethchain" + "github.com/ethereum/eth-go/ethutil" +) + +type PEthereum struct { + stateManager *ethchain.StateManager + blockChain *ethchain.BlockChain + txPool *ethchain.TxPool +} + +func NewPEthereum(eth *eth.Ethereum) *PEthereum { + return &PEthereum{ + eth.StateManager(), + eth.BlockChain(), + eth.TxPool(), + } +} + +func (lib *PEthereum) GetBlock(hexHash string) *PBlock { + hash := ethutil.FromHex(hexHash) + + block := lib.blockChain.GetBlock(hash) + + return &PBlock{Number: int(block.BlockInfo().Number), Hash: ethutil.Hex(block.Hash())} +} + +func (lib *PEthereum) GetKey() string { + return ethutil.Hex(ethutil.Config.Db.GetKeys()[0].Address()) +} + +func (lib *PEthereum) GetStateObject(address string) *PStateObject { + stateObject := lib.stateManager.ProcState().GetContract(ethutil.FromHex(address)) + if stateObject != nil { + return NewPStateObject(stateObject) + } + + // See GetStorage for explanation on "nil" + return NewPStateObject(nil) +} + +func (lib *PEthereum) Transact(key, recipient, valueStr, gasStr, gasPriceStr, dataStr string) (string, error) { + return lib.createTx(key, recipient, valueStr, gasStr, gasPriceStr, dataStr, "") +} + +func (lib *PEthereum) Create(key, valueStr, gasStr, gasPriceStr, initStr, bodyStr string) (string, error) { + return lib.createTx(key, "", valueStr, gasStr, gasPriceStr, initStr, bodyStr) +} + +func (lib *PEthereum) createTx(key, recipient, valueStr, gasStr, gasPriceStr, initStr, scriptStr string) (string, error) { + var hash []byte + var contractCreation bool + if len(recipient) == 0 { + contractCreation = true + } else { + hash = ethutil.FromHex(recipient) + } + + keyPair, err := ethchain.NewKeyPairFromSec([]byte(key)) + if err != nil { + return "", err + } + + value := ethutil.Big(valueStr) + gas := ethutil.Big(gasStr) + gasPrice := ethutil.Big(gasPriceStr) + var tx *ethchain.Transaction + // Compile and assemble the given data + if contractCreation { + initScript, err := Compile(initStr) + if err != nil { + return "", err + } + mainScript, err := Compile(scriptStr) + if err != nil { + return "", err + } + + tx = ethchain.NewContractCreationTx(value, gas, gasPrice, mainScript, initScript) + } else { + /* + lines := strings.Split(dataStr, "\n") + var data []byte + for _, line := range lines { + data = append(data, ethutil.BigToBytes(ethutil.Big(line), 256)...) + } + */ + + tx = ethchain.NewTransactionMessage(hash, value, gas, gasPrice, []byte(initStr)) + } + + acc := lib.stateManager.GetAddrState(keyPair.Address()) + tx.Nonce = acc.Nonce + tx.Sign(keyPair.PrivateKey) + lib.txPool.QueueTransaction(tx) + + if contractCreation { + ethutil.Config.Log.Infof("Contract addr %x", tx.Hash()[12:]) + } else { + ethutil.Config.Log.Infof("Tx hash %x", tx.Hash()) + } + + return ethutil.Hex(tx.Hash()), nil +} diff --git a/utils/types.go b/utils/types.go new file mode 100644 index 000000000..44264aa5e --- /dev/null +++ b/utils/types.go @@ -0,0 +1,83 @@ +package utils + +import ( + "encoding/hex" + "github.com/ethereum/eth-go/ethchain" + "github.com/ethereum/eth-go/ethutil" +) + +// Block interface exposed to QML +type PBlock struct { + Number int + Hash string +} + +// Creates a new QML Block from a chain block +func NewPBlock(block *ethchain.Block) *PBlock { + info := block.BlockInfo() + hash := hex.EncodeToString(block.Hash()) + + return &PBlock{Number: int(info.Number), Hash: hash} +} + +type PTx struct { + Value, Hash, Address string + Contract bool +} + +func NewPTx(tx *ethchain.Transaction) *PTx { + hash := hex.EncodeToString(tx.Hash()) + sender := hex.EncodeToString(tx.Recipient) + isContract := len(tx.Data) > 0 + + return &PTx{Hash: hash, Value: ethutil.CurrencyToString(tx.Value), Address: sender, Contract: isContract} +} + +type PKey struct { + Address string +} + +type PKeyRing struct { + Keys []interface{} +} + +func NewPKeyRing(keys []interface{}) *PKeyRing { + return &PKeyRing{Keys: keys} +} + +type PStateObject struct { + object *ethchain.StateObject +} + +func NewPStateObject(object *ethchain.StateObject) *PStateObject { + return &PStateObject{object: object} +} + +func (c *PStateObject) GetStorage(address string) string { + // Because somehow, even if you return nil to QML it + // still has some magical object so we can't rely on + // undefined or null at the QML side + if c.object != nil { + val := c.object.GetMem(ethutil.Big("0x" + address)) + + return val.BigInt().String() + } + + return "" +} + +func (c *PStateObject) Value() string { + if c.object != nil { + return c.object.Amount.String() + } + + return "" +} + +func (c *PStateObject) Address() string { + if c.object != nil { + return ethutil.Hex(c.object.Address()) + } + + return "" +} -- cgit v1.2.3 From f1da6f0564696f4fb5a6c04d1b9e24ed12432d63 Mon Sep 17 00:00:00 2001 From: obscuren Date: Fri, 2 May 2014 13:35:12 +0200 Subject: Fixed samplecoin --- utils/ethereum.go | 27 +++++++++++++++------------ utils/types.go | 10 +++++++++- 2 files changed, 24 insertions(+), 13 deletions(-) (limited to 'utils') diff --git a/utils/ethereum.go b/utils/ethereum.go index c383c4c91..526795894 100644 --- a/utils/ethereum.go +++ b/utils/ethereum.go @@ -1,6 +1,7 @@ package utils import ( + "fmt" "github.com/ethereum/eth-go" "github.com/ethereum/eth-go/ethchain" "github.com/ethereum/eth-go/ethutil" @@ -28,8 +29,13 @@ func (lib *PEthereum) GetBlock(hexHash string) *PBlock { return &PBlock{Number: int(block.BlockInfo().Number), Hash: ethutil.Hex(block.Hash())} } -func (lib *PEthereum) GetKey() string { - return ethutil.Hex(ethutil.Config.Db.GetKeys()[0].Address()) +func (lib *PEthereum) GetKey() *PKey { + keyPair, err := ethchain.NewKeyPairFromSec(ethutil.Config.Db.GetKeys()[0].PrivateKey) + if err != nil { + return nil + } + + return NewPKey(keyPair) } func (lib *PEthereum) GetStateObject(address string) *PStateObject { @@ -59,7 +65,7 @@ func (lib *PEthereum) createTx(key, recipient, valueStr, gasStr, gasPriceStr, in hash = ethutil.FromHex(recipient) } - keyPair, err := ethchain.NewKeyPairFromSec([]byte(key)) + keyPair, err := ethchain.NewKeyPairFromSec([]byte(ethutil.FromHex(key))) if err != nil { return "", err } @@ -81,15 +87,12 @@ func (lib *PEthereum) createTx(key, recipient, valueStr, gasStr, gasPriceStr, in tx = ethchain.NewContractCreationTx(value, gas, gasPrice, mainScript, initScript) } else { - /* - lines := strings.Split(dataStr, "\n") - var data []byte - for _, line := range lines { - data = append(data, ethutil.BigToBytes(ethutil.Big(line), 256)...) - } - */ - - tx = ethchain.NewTransactionMessage(hash, value, gas, gasPrice, []byte(initStr)) + // Just in case it was submitted as a 0x prefixed string + if initStr[0:2] == "0x" { + initStr = initStr[2:len(initStr)] + } + fmt.Println("DATA:", initStr) + tx = ethchain.NewTransactionMessage(hash, value, gas, gasPrice, ethutil.FromHex(initStr)) } acc := lib.stateManager.GetAddrState(keyPair.Address()) diff --git a/utils/types.go b/utils/types.go index 44264aa5e..0bbc61627 100644 --- a/utils/types.go +++ b/utils/types.go @@ -34,9 +34,16 @@ func NewPTx(tx *ethchain.Transaction) *PTx { } type PKey struct { - Address string + Address string + PrivateKey string + PublicKey string } +func NewPKey(key *ethchain.KeyPair) *PKey { + return &PKey{ethutil.Hex(key.Address()), ethutil.Hex(key.PrivateKey), ethutil.Hex(key.PublicKey)} +} + +/* type PKeyRing struct { Keys []interface{} } @@ -44,6 +51,7 @@ type PKeyRing struct { func NewPKeyRing(keys []interface{}) *PKeyRing { return &PKeyRing{Keys: keys} } +*/ type PStateObject struct { object *ethchain.StateObject -- cgit v1.2.3 From ed64434dcc10347ad9846182ece2d71238138de9 Mon Sep 17 00:00:00 2001 From: obscuren Date: Fri, 2 May 2014 13:55:58 +0200 Subject: Moved public interface --- utils/ethereum.go | 110 ------------------------------------------------------ utils/types.go | 91 -------------------------------------------- 2 files changed, 201 deletions(-) delete mode 100644 utils/ethereum.go delete mode 100644 utils/types.go (limited to 'utils') diff --git a/utils/ethereum.go b/utils/ethereum.go deleted file mode 100644 index 526795894..000000000 --- a/utils/ethereum.go +++ /dev/null @@ -1,110 +0,0 @@ -package utils - -import ( - "fmt" - "github.com/ethereum/eth-go" - "github.com/ethereum/eth-go/ethchain" - "github.com/ethereum/eth-go/ethutil" -) - -type PEthereum struct { - stateManager *ethchain.StateManager - blockChain *ethchain.BlockChain - txPool *ethchain.TxPool -} - -func NewPEthereum(eth *eth.Ethereum) *PEthereum { - return &PEthereum{ - eth.StateManager(), - eth.BlockChain(), - eth.TxPool(), - } -} - -func (lib *PEthereum) GetBlock(hexHash string) *PBlock { - hash := ethutil.FromHex(hexHash) - - block := lib.blockChain.GetBlock(hash) - - return &PBlock{Number: int(block.BlockInfo().Number), Hash: ethutil.Hex(block.Hash())} -} - -func (lib *PEthereum) GetKey() *PKey { - keyPair, err := ethchain.NewKeyPairFromSec(ethutil.Config.Db.GetKeys()[0].PrivateKey) - if err != nil { - return nil - } - - return NewPKey(keyPair) -} - -func (lib *PEthereum) GetStateObject(address string) *PStateObject { - stateObject := lib.stateManager.ProcState().GetContract(ethutil.FromHex(address)) - if stateObject != nil { - return NewPStateObject(stateObject) - } - - // See GetStorage for explanation on "nil" - return NewPStateObject(nil) -} - -func (lib *PEthereum) Transact(key, recipient, valueStr, gasStr, gasPriceStr, dataStr string) (string, error) { - return lib.createTx(key, recipient, valueStr, gasStr, gasPriceStr, dataStr, "") -} - -func (lib *PEthereum) Create(key, valueStr, gasStr, gasPriceStr, initStr, bodyStr string) (string, error) { - return lib.createTx(key, "", valueStr, gasStr, gasPriceStr, initStr, bodyStr) -} - -func (lib *PEthereum) createTx(key, recipient, valueStr, gasStr, gasPriceStr, initStr, scriptStr string) (string, error) { - var hash []byte - var contractCreation bool - if len(recipient) == 0 { - contractCreation = true - } else { - hash = ethutil.FromHex(recipient) - } - - keyPair, err := ethchain.NewKeyPairFromSec([]byte(ethutil.FromHex(key))) - if err != nil { - return "", err - } - - value := ethutil.Big(valueStr) - gas := ethutil.Big(gasStr) - gasPrice := ethutil.Big(gasPriceStr) - var tx *ethchain.Transaction - // Compile and assemble the given data - if contractCreation { - initScript, err := Compile(initStr) - if err != nil { - return "", err - } - mainScript, err := Compile(scriptStr) - if err != nil { - return "", err - } - - tx = ethchain.NewContractCreationTx(value, gas, gasPrice, mainScript, initScript) - } else { - // Just in case it was submitted as a 0x prefixed string - if initStr[0:2] == "0x" { - initStr = initStr[2:len(initStr)] - } - fmt.Println("DATA:", initStr) - tx = ethchain.NewTransactionMessage(hash, value, gas, gasPrice, ethutil.FromHex(initStr)) - } - - acc := lib.stateManager.GetAddrState(keyPair.Address()) - tx.Nonce = acc.Nonce - tx.Sign(keyPair.PrivateKey) - lib.txPool.QueueTransaction(tx) - - if contractCreation { - ethutil.Config.Log.Infof("Contract addr %x", tx.Hash()[12:]) - } else { - ethutil.Config.Log.Infof("Tx hash %x", tx.Hash()) - } - - return ethutil.Hex(tx.Hash()), nil -} diff --git a/utils/types.go b/utils/types.go deleted file mode 100644 index 0bbc61627..000000000 --- a/utils/types.go +++ /dev/null @@ -1,91 +0,0 @@ -package utils - -import ( - "encoding/hex" - "github.com/ethereum/eth-go/ethchain" - "github.com/ethereum/eth-go/ethutil" -) - -// Block interface exposed to QML -type PBlock struct { - Number int - Hash string -} - -// Creates a new QML Block from a chain block -func NewPBlock(block *ethchain.Block) *PBlock { - info := block.BlockInfo() - hash := hex.EncodeToString(block.Hash()) - - return &PBlock{Number: int(info.Number), Hash: hash} -} - -type PTx struct { - Value, Hash, Address string - Contract bool -} - -func NewPTx(tx *ethchain.Transaction) *PTx { - hash := hex.EncodeToString(tx.Hash()) - sender := hex.EncodeToString(tx.Recipient) - isContract := len(tx.Data) > 0 - - return &PTx{Hash: hash, Value: ethutil.CurrencyToString(tx.Value), Address: sender, Contract: isContract} -} - -type PKey struct { - Address string - PrivateKey string - PublicKey string -} - -func NewPKey(key *ethchain.KeyPair) *PKey { - return &PKey{ethutil.Hex(key.Address()), ethutil.Hex(key.PrivateKey), ethutil.Hex(key.PublicKey)} -} - -/* -type PKeyRing struct { - Keys []interface{} -} - -func NewPKeyRing(keys []interface{}) *PKeyRing { - return &PKeyRing{Keys: keys} -} -*/ - -type PStateObject struct { - object *ethchain.StateObject -} - -func NewPStateObject(object *ethchain.StateObject) *PStateObject { - return &PStateObject{object: object} -} - -func (c *PStateObject) GetStorage(address string) string { - // Because somehow, even if you return nil to QML it - // still has some magical object so we can't rely on - // undefined or null at the QML side - if c.object != nil { - val := c.object.GetMem(ethutil.Big("0x" + address)) - - return val.BigInt().String() - } - - return "" -} - -func (c *PStateObject) Value() string { - if c.object != nil { - return c.object.Amount.String() - } - - return "" -} - -func (c *PStateObject) Address() string { - if c.object != nil { - return ethutil.Hex(c.object.Address()) - } - - return "" -} -- cgit v1.2.3 From 23fc50c61b99735263eb682eb992c174eceea632 Mon Sep 17 00:00:00 2001 From: obscuren Date: Sat, 10 May 2014 16:22:57 +0200 Subject: Upgraded to new mutan --- utils/compile.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'utils') diff --git a/utils/compile.go b/utils/compile.go index 6d75f73d1..967bd099b 100644 --- a/utils/compile.go +++ b/utils/compile.go @@ -24,7 +24,7 @@ func Compile(script string) ([]byte, error) { func CompileScript(script string) ([]byte, []byte, error) { // Preprocess - mainInput, initInput := mutan.PreProcess(script) + mainInput, initInput := mutan.PreParse(script) // Compile main script mainScript, err := Compile(mainInput) if err != nil { -- cgit v1.2.3 From e8147cf7c6f508910698e6743ad347c78010ffe3 Mon Sep 17 00:00:00 2001 From: Maran Date: Wed, 14 May 2014 12:41:30 +0200 Subject: Refactored mining into utils and exposed it to ethereal. Partly fixes #43 --- utils/cmd.go | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 utils/cmd.go (limited to 'utils') diff --git a/utils/cmd.go b/utils/cmd.go new file mode 100644 index 000000000..a99fd9eed --- /dev/null +++ b/utils/cmd.go @@ -0,0 +1,31 @@ +package utils + +import ( + "encoding/hex" + "github.com/ethereum/eth-go" + "github.com/ethereum/eth-go/ethchain" + "github.com/ethereum/eth-go/ethminer" + _ "github.com/ethereum/eth-go/ethrpc" + "github.com/ethereum/eth-go/ethutil" + "log" +) + +func DoMining(ethereum *eth.Ethereum) { + // Set Mining status + ethereum.Mining = true + + log.Println("Miner started") + + // Fake block mining. It broadcasts a new block every 5 seconds + go func() { + data, _ := ethutil.Config.Db.Get([]byte("KeyRing")) + keyRing := ethutil.NewValueFromBytes(data) + addr := keyRing.Get(0).Bytes() + + pair, _ := ethchain.NewKeyPairFromSec(ethutil.FromHex(hex.EncodeToString(addr))) + + miner := ethminer.NewDefaultMiner(pair.Address(), ethereum) + miner.Start() + + }() +} -- cgit v1.2.3 From 2012e0c67abd8e3012a3eb1fae2e282e2a442d01 Mon Sep 17 00:00:00 2001 From: Maran Date: Wed, 14 May 2014 13:26:15 +0200 Subject: Rewritten a check to only start mining once we are caught up with all peers --- utils/cmd.go | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) (limited to 'utils') diff --git a/utils/cmd.go b/utils/cmd.go index a99fd9eed..44924ce91 100644 --- a/utils/cmd.go +++ b/utils/cmd.go @@ -8,24 +8,27 @@ import ( _ "github.com/ethereum/eth-go/ethrpc" "github.com/ethereum/eth-go/ethutil" "log" + "time" ) func DoMining(ethereum *eth.Ethereum) { // Set Mining status ethereum.Mining = true - log.Println("Miner started") - - // Fake block mining. It broadcasts a new block every 5 seconds go func() { + // Give it some time to connect with peers + time.Sleep(3 * time.Second) + + for ethereum.IsUpToDate() == false { + time.Sleep(5 * time.Second) + } + log.Println("Miner started") + data, _ := ethutil.Config.Db.Get([]byte("KeyRing")) keyRing := ethutil.NewValueFromBytes(data) addr := keyRing.Get(0).Bytes() - pair, _ := ethchain.NewKeyPairFromSec(ethutil.FromHex(hex.EncodeToString(addr))) - miner := ethminer.NewDefaultMiner(pair.Address(), ethereum) miner.Start() - }() } -- cgit v1.2.3 From 9fce273ce97a8db091a0bf9d0b503a2ea7261f81 Mon Sep 17 00:00:00 2001 From: Maran Date: Wed, 14 May 2014 13:32:49 +0200 Subject: Refactored RPC client to utils so it can be reused --- utils/cmd.go | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) (limited to 'utils') diff --git a/utils/cmd.go b/utils/cmd.go index 44924ce91..5a100ca4f 100644 --- a/utils/cmd.go +++ b/utils/cmd.go @@ -5,12 +5,23 @@ import ( "github.com/ethereum/eth-go" "github.com/ethereum/eth-go/ethchain" "github.com/ethereum/eth-go/ethminer" - _ "github.com/ethereum/eth-go/ethrpc" + "github.com/ethereum/eth-go/ethpub" + "github.com/ethereum/eth-go/ethrpc" "github.com/ethereum/eth-go/ethutil" "log" "time" ) +func DoRpc(ethereum *eth.Ethereum, RpcPort int) { + var err error + ethereum.RpcServer, err = ethrpc.NewJsonRpcServer(ethpub.NewPEthereum(ethereum), RpcPort) + if err != nil { + log.Println("Could not start RPC interface:", err) + } else { + go ethereum.RpcServer.Start() + } +} + func DoMining(ethereum *eth.Ethereum) { // Set Mining status ethereum.Mining = true -- cgit v1.2.3 From f18ec51cb3959cc662bfc7b84314cd1d3b1541b5 Mon Sep 17 00:00:00 2001 From: obscuren Date: Wed, 14 May 2014 13:55:08 +0200 Subject: Switched to new keyring methods --- utils/cmd.go | 11 +++-------- utils/keys.go | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+), 8 deletions(-) (limited to 'utils') diff --git a/utils/cmd.go b/utils/cmd.go index a99fd9eed..654014169 100644 --- a/utils/cmd.go +++ b/utils/cmd.go @@ -1,9 +1,7 @@ package utils import ( - "encoding/hex" "github.com/ethereum/eth-go" - "github.com/ethereum/eth-go/ethchain" "github.com/ethereum/eth-go/ethminer" _ "github.com/ethereum/eth-go/ethrpc" "github.com/ethereum/eth-go/ethutil" @@ -18,13 +16,10 @@ func DoMining(ethereum *eth.Ethereum) { // Fake block mining. It broadcasts a new block every 5 seconds go func() { - data, _ := ethutil.Config.Db.Get([]byte("KeyRing")) - keyRing := ethutil.NewValueFromBytes(data) - addr := keyRing.Get(0).Bytes() + keyPair := ethutil.GetKeyRing().Get(0) + addr := keyPair.Address() - pair, _ := ethchain.NewKeyPairFromSec(ethutil.FromHex(hex.EncodeToString(addr))) - - miner := ethminer.NewDefaultMiner(pair.Address(), ethereum) + miner := ethminer.NewDefaultMiner(addr, ethereum) miner.Start() }() diff --git a/utils/keys.go b/utils/keys.go index 2f39c10b2..1c0f6a9d6 100644 --- a/utils/keys.go +++ b/utils/keys.go @@ -6,6 +6,60 @@ import ( "github.com/obscuren/secp256k1-go" ) +func CreateKeyPair(force bool) { + if force { + ethutil.GetKeyRing().Reset() + fmt.Println("resetting") + } + + if ethutil.GetKeyRing().Get(0) == nil { + _, prv := secp256k1.GenerateKeyPair() + + keyPair, err := ethutil.GetKeyRing().NewKeyPair(prv) + if err != nil { + panic(err) + } + + mne := ethutil.MnemonicEncode(ethutil.Hex(keyPair.PrivateKey)) + + fmt.Printf(` +Generating new address and keypair. +Please keep your keys somewhere save. + +++++++++++++++++ KeyRing +++++++++++++++++++ +addr: %x +prvk: %x +pubk: %x +++++++++++++++++++++++++++++++++++++++++++++ +save these words so you can restore your account later: %s +`, keyPair.Address(), keyPair.PrivateKey, keyPair.PublicKey, mne) + } +} + +func ImportPrivateKey(sec string) { + ethutil.GetKeyRing().Reset() + + keyPair, err := ethutil.GetKeyRing().NewKeyPair(ethutil.FromHex(sec)) + if err != nil { + panic(err) + } + + mne := ethutil.MnemonicEncode(ethutil.Hex(keyPair.PrivateKey)) + + fmt.Printf(` +Generating new address and keypair. +Please keep your keys somewhere save. + +++++++++++++++++ KeyRing +++++++++++++++++++ +addr: %x +prvk: %x +pubk: %x +++++++++++++++++++++++++++++++++++++++++++++ +save these words so you can restore your account later: %s +`, keyPair.Address(), keyPair.PrivateKey, keyPair.PublicKey, mne) +} + +/* func CreateKeyPair(force bool) { data, _ := ethutil.Config.Db.Get([]byte("KeyRing")) if len(data) == 0 || force { @@ -28,7 +82,9 @@ save these words so you can restore your account later: %s } } +*/ +/* func ImportPrivateKey(prvKey string) { key := ethutil.FromHex(prvKey) msg := []byte("tmp") @@ -49,3 +105,4 @@ pubk: %x `, pair.Address(), key, pub) } +*/ -- cgit v1.2.3 From 2c7b625daaf062192db2fa604344f79c1bdbb232 Mon Sep 17 00:00:00 2001 From: Maran Date: Wed, 14 May 2014 13:55:55 +0200 Subject: Make sure we have a coinbase address to mine with --- utils/cmd.go | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) (limited to 'utils') diff --git a/utils/cmd.go b/utils/cmd.go index 5a100ca4f..66cfbeff9 100644 --- a/utils/cmd.go +++ b/utils/cmd.go @@ -26,6 +26,16 @@ func DoMining(ethereum *eth.Ethereum) { // Set Mining status ethereum.Mining = true + data, _ := ethutil.Config.Db.Get([]byte("KeyRing")) + if len(data) == 0 { + log.Println("No address found, can't start mining") + return + } + + keyRing := ethutil.NewValueFromBytes(data) + addr := keyRing.Get(0).Bytes() + pair, _ := ethchain.NewKeyPairFromSec(ethutil.FromHex(hex.EncodeToString(addr))) + go func() { // Give it some time to connect with peers time.Sleep(3 * time.Second) @@ -35,10 +45,6 @@ func DoMining(ethereum *eth.Ethereum) { } log.Println("Miner started") - data, _ := ethutil.Config.Db.Get([]byte("KeyRing")) - keyRing := ethutil.NewValueFromBytes(data) - addr := keyRing.Get(0).Bytes() - pair, _ := ethchain.NewKeyPairFromSec(ethutil.FromHex(hex.EncodeToString(addr))) miner := ethminer.NewDefaultMiner(pair.Address(), ethereum) miner.Start() }() -- cgit v1.2.3 From 770808ce0d44cadfedbe01694c836be2eaf0e82c Mon Sep 17 00:00:00 2001 From: obscuren Date: Sat, 17 May 2014 15:15:46 +0200 Subject: Readline repl for linux & osx --- utils/cmd.go | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) (limited to 'utils') diff --git a/utils/cmd.go b/utils/cmd.go index 8395ac8fc..62e8f31dc 100644 --- a/utils/cmd.go +++ b/utils/cmd.go @@ -35,9 +35,11 @@ func DoMining(ethereum *eth.Ethereum) { // Give it some time to connect with peers time.Sleep(3 * time.Second) - for ethereum.IsUpToDate() == false { - time.Sleep(5 * time.Second) - } + /* + for ethereum.IsUpToDate() == false { + time.Sleep(5 * time.Second) + } + */ log.Println("Miner started") miner := ethminer.NewDefaultMiner(addr, ethereum) -- cgit v1.2.3 From 30842eb8d013856039c128f3a3303c1fc6f833c2 Mon Sep 17 00:00:00 2001 From: obscuren Date: Mon, 19 May 2014 12:14:47 +0200 Subject: Changed logging --- utils/cmd.go | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) (limited to 'utils') diff --git a/utils/cmd.go b/utils/cmd.go index 62e8f31dc..f163575da 100644 --- a/utils/cmd.go +++ b/utils/cmd.go @@ -6,7 +6,6 @@ import ( "github.com/ethereum/eth-go/ethpub" "github.com/ethereum/eth-go/ethrpc" "github.com/ethereum/eth-go/ethutil" - "log" "time" ) @@ -14,7 +13,7 @@ func DoRpc(ethereum *eth.Ethereum, RpcPort int) { var err error ethereum.RpcServer, err = ethrpc.NewJsonRpcServer(ethpub.NewPEthereum(ethereum), RpcPort) if err != nil { - log.Println("Could not start RPC interface:", err) + ethutil.Config.Log.Infoln("Could not start RPC interface:", err) } else { go ethereum.RpcServer.Start() } @@ -25,7 +24,7 @@ func DoMining(ethereum *eth.Ethereum) { ethereum.Mining = true if ethutil.GetKeyRing().Len() == 0 { - log.Println("No address found, can't start mining") + ethutil.Config.Log.Infoln("No address found, can't start mining") return } keyPair := ethutil.GetKeyRing().Get(0) @@ -40,7 +39,7 @@ func DoMining(ethereum *eth.Ethereum) { time.Sleep(5 * time.Second) } */ - log.Println("Miner started") + ethutil.Config.Log.Infoln("Miner started") miner := ethminer.NewDefaultMiner(addr, ethereum) miner.Start() -- cgit v1.2.3 From 0bccf1c3cd9576724cbd387922997ebd6bbcf898 Mon Sep 17 00:00:00 2001 From: Maran Date: Wed, 21 May 2014 11:45:19 +0200 Subject: Wait with mining until up to date --- utils/cmd.go | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) (limited to 'utils') diff --git a/utils/cmd.go b/utils/cmd.go index f163575da..28597194f 100644 --- a/utils/cmd.go +++ b/utils/cmd.go @@ -34,11 +34,10 @@ func DoMining(ethereum *eth.Ethereum) { // Give it some time to connect with peers time.Sleep(3 * time.Second) - /* - for ethereum.IsUpToDate() == false { - time.Sleep(5 * time.Second) - } - */ + for ethereum.IsUpToDate() == false { + time.Sleep(5 * time.Second) + } + ethutil.Config.Log.Infoln("Miner started") miner := ethminer.NewDefaultMiner(addr, ethereum) -- cgit v1.2.3 From 01b833146f3afa214586a1ffb710546a5e4cc90a Mon Sep 17 00:00:00 2001 From: obscuren Date: Thu, 22 May 2014 00:25:48 +0200 Subject: Added mining stop and start --- utils/cmd.go | 38 ++++++++++++++++++++++++++++++-------- 1 file changed, 30 insertions(+), 8 deletions(-) (limited to 'utils') diff --git a/utils/cmd.go b/utils/cmd.go index f163575da..98005d7de 100644 --- a/utils/cmd.go +++ b/utils/cmd.go @@ -19,6 +19,8 @@ func DoRpc(ethereum *eth.Ethereum, RpcPort int) { } } +var miner ethminer.Miner + func DoMining(ethereum *eth.Ethereum) { // Set Mining status ethereum.Mining = true @@ -31,17 +33,37 @@ func DoMining(ethereum *eth.Ethereum) { addr := keyPair.Address() go func() { + ethutil.Config.Log.Infoln("Miner started") + + miner = ethminer.NewDefaultMiner(addr, ethereum) + // Give it some time to connect with peers time.Sleep(3 * time.Second) - /* - for ethereum.IsUpToDate() == false { - time.Sleep(5 * time.Second) - } - */ - ethutil.Config.Log.Infoln("Miner started") - - miner := ethminer.NewDefaultMiner(addr, ethereum) miner.Start() }() } + +func StopMining(ethereum *eth.Ethereum) bool { + if ethereum.Mining { + miner.Stop() + + ethutil.Config.Log.Infoln("Miner stopped") + + ethereum.Mining = false + + return true + } + + return false +} + +func StartMining(ethereum *eth.Ethereum) bool { + if !ethereum.Mining { + DoMining(ethereum) + + return true + } + + return false +} -- cgit v1.2.3 From e7c9b86a5aba022afd812f1a4fb554ee17a74bbd Mon Sep 17 00:00:00 2001 From: obscuren Date: Fri, 30 May 2014 13:28:31 +0200 Subject: Improved UI * Added mining button --- utils/cmd.go | 2 -- 1 file changed, 2 deletions(-) (limited to 'utils') diff --git a/utils/cmd.go b/utils/cmd.go index f8b7b5fe2..e1fc0fc00 100644 --- a/utils/cmd.go +++ b/utils/cmd.go @@ -33,8 +33,6 @@ func DoMining(ethereum *eth.Ethereum) { addr := keyPair.Address() go func() { - ethutil.Config.Log.Infoln("Miner started") - miner = ethminer.NewDefaultMiner(addr, ethereum) // Give it some time to connect with peers -- cgit v1.2.3 From 176b7802510a667b8973f2be232f7a8213b3474b Mon Sep 17 00:00:00 2001 From: obscuren Date: Mon, 23 Jun 2014 11:28:05 +0200 Subject: Added a execBlock method which replays the given block --- utils/cmd.go | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) (limited to 'utils') diff --git a/utils/cmd.go b/utils/cmd.go index e1fc0fc00..e66bb2612 100644 --- a/utils/cmd.go +++ b/utils/cmd.go @@ -38,9 +38,11 @@ func DoMining(ethereum *eth.Ethereum) { // Give it some time to connect with peers time.Sleep(3 * time.Second) - for ethereum.IsUpToDate() == false { - time.Sleep(5 * time.Second) - } + /* + for ethereum.IsUpToDate() == false { + time.Sleep(5 * time.Second) + } + */ ethutil.Config.Log.Infoln("Miner started") -- cgit v1.2.3 From 1024766514eea7bb628ec6e5ed974e997b8faefc Mon Sep 17 00:00:00 2001 From: zelig Date: Mon, 23 Jun 2014 12:20:59 +0100 Subject: refactor cli and gui wrapper code. Details: - all cli functions shared between ethereum and ethereal abstracted to utils/ cmd.go (should be ethcommon or shared or sth) - simplify main() now readable stepwise - rename main wrapper files to main.go - rename commmand line args definition file from config.go to flags.go - rename Do -> Start to parallel option names - register interrupt for rpc server stop - fix interrupt stopping js repl and ethereum - register interrupt for mining stop - custom config file option from command line - debug option from command line - loglevel option from command line - changed ethutil.Config API - default datadir and default config file set together with other flag defaults in wrappers - default assetpath set together with other command line flags defaults in gui wrapper (not in ethutil.Config or ui/ui_lib) - options precedence: default < config file < environment variables < command line --- utils/cmd.go | 250 +++++++++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 200 insertions(+), 50 deletions(-) (limited to 'utils') diff --git a/utils/cmd.go b/utils/cmd.go index e1fc0fc00..39233d586 100644 --- a/utils/cmd.go +++ b/utils/cmd.go @@ -1,74 +1,224 @@ package utils import ( - "github.com/ethereum/eth-go" - "github.com/ethereum/eth-go/ethminer" - "github.com/ethereum/eth-go/ethpub" - "github.com/ethereum/eth-go/ethrpc" - "github.com/ethereum/eth-go/ethutil" - "time" + "github.com/ethereum/eth-go" + "github.com/ethereum/eth-go/ethminer" + "github.com/ethereum/eth-go/ethpub" + "github.com/ethereum/eth-go/ethrpc" + "github.com/ethereum/eth-go/ethutil" + "github.com/ethereum/eth-go/ethlog" + "log" + "io" + "path" + "os" + "os/signal" + "fmt" + "time" + "strings" ) -func DoRpc(ethereum *eth.Ethereum, RpcPort int) { - var err error - ethereum.RpcServer, err = ethrpc.NewJsonRpcServer(ethpub.NewPEthereum(ethereum), RpcPort) - if err != nil { - ethutil.Config.Log.Infoln("Could not start RPC interface:", err) - } else { - go ethereum.RpcServer.Start() - } +var logger = ethlog.NewLogger("CLI") + +// Register interrupt handlers +func RegisterInterrupt(cb func(os.Signal)) { + go func() { + // Buffered chan of one is enough + c := make(chan os.Signal, 1) + // Notify about interrupts for now + signal.Notify(c, os.Interrupt) + for sig := range c { + cb(sig) + } + }() } -var miner ethminer.Miner - -func DoMining(ethereum *eth.Ethereum) { - // Set Mining status - ethereum.Mining = true +func AbsolutePath(Datadir string, filename string) string { + if path.IsAbs(filename) { + return filename + } + return path.Join(Datadir, filename) +} - if ethutil.GetKeyRing().Len() == 0 { - ethutil.Config.Log.Infoln("No address found, can't start mining") - return - } - keyPair := ethutil.GetKeyRing().Get(0) - addr := keyPair.Address() +func openLogFile (Datadir string, filename string) *os.File { + path := 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)) + } + return file +} - go func() { - miner = ethminer.NewDefaultMiner(addr, ethereum) +func confirm (message string) bool { + fmt.Println(message, "Are you sure? (y/n)") + var r string + fmt.Scanln(&r) + for ; ; fmt.Scanln(&r) { + if r == "n" || r == "y" { + break + } else { + fmt.Printf("Yes or no?", r) + } + } + return r == "y" +} - // Give it some time to connect with peers - time.Sleep(3 * time.Second) +func InitDataDir(Datadir string) { + _, err := os.Stat(Datadir) + if err != nil { + if os.IsNotExist(err) { + fmt.Printf("Debug logging directory '%s' doesn't exist, creating it\n", Datadir) + os.Mkdir(Datadir, 0777) + } + } +} - for ethereum.IsUpToDate() == false { - time.Sleep(5 * time.Second) - } +func InitLogging (Datadir string, LogFile string, LogLevel int, DebugFile string) { + var writer io.Writer + if LogFile == "" { + writer = os.Stdout + } else { + writer = openLogFile(Datadir, LogFile) + } + ethlog.AddLogSystem(ethlog.NewStdLogSystem(writer, log.LstdFlags, ethlog.LogLevel(LogLevel))) + if DebugFile != "" { + writer = openLogFile(Datadir, DebugFile) + ethlog.AddLogSystem(ethlog.NewStdLogSystem(writer, log.LstdFlags, ethlog.DebugLevel)) + } +} - ethutil.Config.Log.Infoln("Miner started") +func InitConfig(ConfigFile string, Datadir string, Identifier string, EnvPrefix string) { + ethutil.ReadConfig(ConfigFile, Datadir, Identifier, EnvPrefix) + ethutil.Config.Set("rpcport", "700") +} - miner := ethminer.NewDefaultMiner(addr, ethereum) - miner.Start() - }() +func exit(status int) { + ethlog.Flush() + os.Exit(status) } -func StopMining(ethereum *eth.Ethereum) bool { - if ethereum.Mining { - miner.Stop() +func NewEthereum(UseUPnP bool, OutboundPort string, MaxPeer int) *eth.Ethereum { + ethereum, err := eth.New(eth.CapDefault, UseUPnP) + if err != nil { + logger.Fatalln("eth start err:", err) + } + ethereum.Port = OutboundPort + ethereum.MaxPeers = MaxPeer + return ethereum +} - ethutil.Config.Log.Infoln("Miner stopped") +func StartEthereum(ethereum *eth.Ethereum, UseSeed bool) { + logger.Infof("Starting Ethereum v%s", ethutil.Config.Ver) + ethereum.Start(UseSeed) + // Wait for shutdown + ethereum.WaitForShutdown() + RegisterInterrupt(func(sig os.Signal) { + logger.Errorf("Shutting down (%v) ... \n", sig) + ethereum.Stop() + ethlog.Flush() + }) +} - ethereum.Mining = false +func ShowGenesis(ethereum *eth.Ethereum) { + logger.Infoln(ethereum.BlockChain().Genesis()) + exit(0) +} - return true - } +func KeyTasks(GenAddr bool, ImportKey string, ExportKey bool, NonInteractive bool) { + switch { + case GenAddr: + if NonInteractive || confirm("This action overwrites your old private key.") { + CreateKeyPair(true) + } + exit(0) + case len(ImportKey) > 0: + if NonInteractive || confirm("This action overwrites your old private key.") { + // import should be from file + mnemonic := strings.Split(ImportKey, " ") + if len(mnemonic) == 24 { + logger.Infoln("Got mnemonic key, importing.") + key := ethutil.MnemonicDecode(mnemonic) + ImportPrivateKey(key) + } else if len(mnemonic) == 1 { + logger.Infoln("Got hex key, importing.") + ImportPrivateKey(ImportKey) + } else { + logger.Errorln("Did not recognise format, exiting.") + } + } + exit(0) + case ExportKey: // this should be exporting to a filename + keyPair := ethutil.GetKeyRing().Get(0) + fmt.Printf(` +Generating new address and keypair. +Please keep your keys somewhere save. + +++++++++++++++++ KeyRing +++++++++++++++++++ +addr: %x +prvk: %x +pubk: %x +++++++++++++++++++++++++++++++++++++++++++++ +save these words so you can restore your account later: %s +`, keyPair.Address(), keyPair.PrivateKey, keyPair.PublicKey) + + exit(0) + default: + // Creates a keypair if none exists + CreateKeyPair(false) + } +} - return false +func StartRpc(ethereum *eth.Ethereum, RpcPort int) { + var err error + ethereum.RpcServer, err = ethrpc.NewJsonRpcServer(ethpub.NewPEthereum(ethereum), RpcPort) + if err != nil { + logger.Errorf("Could not start RPC interface (port %v): %v", RpcPort, err) + } else { + go ethereum.RpcServer.Start() + RegisterInterrupt(func(os.Signal) { + ethereum.RpcServer.Stop() + }) + } } -func StartMining(ethereum *eth.Ethereum) bool { - if !ethereum.Mining { - DoMining(ethereum) +var miner ethminer.Miner - return true - } +func StartMining(ethereum *eth.Ethereum) bool { + if !ethereum.Mining { + ethereum.Mining = true + + if ethutil.GetKeyRing().Len() == 0 { + logger.Errorln("No address found, can't start mining") + ethereum.Mining = false + return true //???? + } + keyPair := ethutil.GetKeyRing().Get(0) + addr := keyPair.Address() + + go func() { + miner = ethminer.NewDefaultMiner(addr, ethereum) + // Give it some time to connect with peers + time.Sleep(3 * time.Second) + for ethereum.IsUpToDate() == false { + time.Sleep(5 * time.Second) + } + logger.Infoln("Miner started") + miner := ethminer.NewDefaultMiner(addr, ethereum) + miner.Start() + }() + RegisterInterrupt(func(os.Signal) { + StopMining(ethereum) + }) + return true + } + return false +} - return false +func StopMining(ethereum *eth.Ethereum) bool { + if ethereum.Mining { + miner.Stop() + logger.Infoln("Miner stopped") + ethereum.Mining = false + return true + } + return false } -- cgit v1.2.3 From 1e965cb8f5c63d73a5aac1556a2638345ba2824c Mon Sep 17 00:00:00 2001 From: obscuren Date: Wed, 25 Jun 2014 09:47:11 +0200 Subject: Moved BlockDo to utils --- utils/cmd.go | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) (limited to 'utils') diff --git a/utils/cmd.go b/utils/cmd.go index e66bb2612..368f2381e 100644 --- a/utils/cmd.go +++ b/utils/cmd.go @@ -1,6 +1,7 @@ package utils import ( + "fmt" "github.com/ethereum/eth-go" "github.com/ethereum/eth-go/ethminer" "github.com/ethereum/eth-go/ethpub" @@ -74,3 +75,21 @@ func StartMining(ethereum *eth.Ethereum) bool { return false } + +// Replay block +func BlockDo(ethereum *eth.Ethereum, hash []byte) error { + block := ethereum.BlockChain().GetBlock(hash) + if block == nil { + return fmt.Errorf("unknown block %x", hash) + } + + parent := ethereum.BlockChain().GetBlock(block.PrevHash) + + _, err := ethereum.StateManager().ApplyDiff(parent.State(), parent, block) + if err != nil { + return err + } + + return nil + +} -- cgit v1.2.3 From 1268413ba7f7a3bc0c60fbe47e582864b2de8ccd Mon Sep 17 00:00:00 2001 From: obscuren Date: Wed, 25 Jun 2014 17:26:16 +0200 Subject: Removed old compile methods --- utils/compile.go | 41 ----------------------------------------- 1 file changed, 41 deletions(-) delete mode 100644 utils/compile.go (limited to 'utils') diff --git a/utils/compile.go b/utils/compile.go deleted file mode 100644 index 967bd099b..000000000 --- a/utils/compile.go +++ /dev/null @@ -1,41 +0,0 @@ -package utils - -import ( - "fmt" - "github.com/obscuren/mutan" - "strings" -) - -// General compile function -func Compile(script string) ([]byte, error) { - byteCode, errors := mutan.Compile(strings.NewReader(script), false) - if len(errors) > 0 { - var errs string - for _, er := range errors { - if er != nil { - errs += er.Error() - } - } - return nil, fmt.Errorf("%v", errs) - } - - return byteCode, nil -} - -func CompileScript(script string) ([]byte, []byte, error) { - // Preprocess - mainInput, initInput := mutan.PreParse(script) - // Compile main script - mainScript, err := Compile(mainInput) - if err != nil { - return nil, nil, err - } - - // Compile init script - initScript, err := Compile(initInput) - if err != nil { - return nil, nil, err - } - - return mainScript, initScript, nil -} -- cgit v1.2.3 From 2f96652bb408e65c205317403d749ba9a395c6bb Mon Sep 17 00:00:00 2001 From: zelig Date: Thu, 26 Jun 2014 10:47:45 +0100 Subject: interrupt handlers now ordered --- utils/cmd.go | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) (limited to 'utils') diff --git a/utils/cmd.go b/utils/cmd.go index 34716b94a..da05c6d83 100644 --- a/utils/cmd.go +++ b/utils/cmd.go @@ -18,16 +18,23 @@ import ( ) var logger = ethlog.NewLogger("CLI") +var interruptCallbacks = []func(os.Signal){} -// Register interrupt handlers +// Register interrupt handlers callbacks func RegisterInterrupt(cb func(os.Signal)) { + interruptCallbacks = append(interruptCallbacks, cb) +} + +// go routine that call interrupt handlers in order of registering +func HandleInterrupt() { + c := make(chan os.Signal, 1) go func() { - // Buffered chan of one is enough - c := make(chan os.Signal, 1) - // Notify about interrupts for now signal.Notify(c, os.Interrupt) for sig := range c { - cb(sig) + logger.Errorf("Shutting down (%v) ... \n", sig) + for _, cb := range interruptCallbacks { + cb(sig) + } } }() } @@ -109,13 +116,12 @@ func NewEthereum(UseUPnP bool, OutboundPort string, MaxPeer int) *eth.Ethereum { func StartEthereum(ethereum *eth.Ethereum, UseSeed bool) { logger.Infof("Starting Ethereum v%s", ethutil.Config.Ver) ethereum.Start(UseSeed) - // Wait for shutdown - ethereum.WaitForShutdown() RegisterInterrupt(func(sig os.Signal) { - logger.Errorf("Shutting down (%v) ... \n", sig) ethereum.Stop() ethlog.Flush() }) + // this blocks the thread + ethereum.WaitForShutdown() } func ShowGenesis(ethereum *eth.Ethereum) { @@ -174,9 +180,6 @@ func StartRpc(ethereum *eth.Ethereum, RpcPort int) { logger.Errorf("Could not start RPC interface (port %v): %v", RpcPort, err) } else { go ethereum.RpcServer.Start() - RegisterInterrupt(func(os.Signal) { - ethereum.RpcServer.Stop() - }) } } -- cgit v1.2.3 From 21d86ca486a88c936a1fe71f78d76c78df36a7eb Mon Sep 17 00:00:00 2001 From: zelig Date: Thu, 26 Jun 2014 16:26:14 +0100 Subject: gui stop - introduce gui.Stop() - remember state with open - stopping ethereum stack is not gui concern, moved to main - stopping mining, gui and ethereum handled via interrupt callbacks - ^C triggers exactly the same behaviour as quit via menu --- utils/cmd.go | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) (limited to 'utils') diff --git a/utils/cmd.go b/utils/cmd.go index da05c6d83..db5ec5b48 100644 --- a/utils/cmd.go +++ b/utils/cmd.go @@ -32,13 +32,17 @@ func HandleInterrupt() { signal.Notify(c, os.Interrupt) for sig := range c { logger.Errorf("Shutting down (%v) ... \n", sig) - for _, cb := range interruptCallbacks { - cb(sig) - } + RunInterruptCallbacks(sig) } }() } +func RunInterruptCallbacks(sig os.Signal) { + for _, cb := range interruptCallbacks { + cb(sig) + } +} + func AbsolutePath(Datadir string, filename string) string { if path.IsAbs(filename) { return filename @@ -94,6 +98,7 @@ func InitLogging (Datadir string, LogFile string, LogLevel int, DebugFile string } func InitConfig(ConfigFile string, Datadir string, Identifier string, EnvPrefix string) { + InitDataDir(Datadir) ethutil.ReadConfig(ConfigFile, Datadir, Identifier, EnvPrefix) ethutil.Config.Set("rpcport", "700") } @@ -120,8 +125,6 @@ func StartEthereum(ethereum *eth.Ethereum, UseSeed bool) { ethereum.Stop() ethlog.Flush() }) - // this blocks the thread - ethereum.WaitForShutdown() } func ShowGenesis(ethereum *eth.Ethereum) { -- cgit v1.2.3 From ae5ace16190d48bfe7a0364fdb0b51644518ec42 Mon Sep 17 00:00:00 2001 From: zelig Date: Thu, 26 Jun 2014 18:41:36 +0100 Subject: go fmt --- utils/cmd.go | 326 +++++++++++++++++++++++++++++------------------------------ 1 file changed, 163 insertions(+), 163 deletions(-) (limited to 'utils') diff --git a/utils/cmd.go b/utils/cmd.go index db5ec5b48..c084542b4 100644 --- a/utils/cmd.go +++ b/utils/cmd.go @@ -1,20 +1,20 @@ package utils import ( - "github.com/ethereum/eth-go" - "github.com/ethereum/eth-go/ethminer" - "github.com/ethereum/eth-go/ethpub" - "github.com/ethereum/eth-go/ethrpc" - "github.com/ethereum/eth-go/ethutil" - "github.com/ethereum/eth-go/ethlog" - "log" - "io" - "path" - "os" - "os/signal" - "fmt" - "time" - "strings" + "fmt" + "github.com/ethereum/eth-go" + "github.com/ethereum/eth-go/ethlog" + "github.com/ethereum/eth-go/ethminer" + "github.com/ethereum/eth-go/ethpub" + "github.com/ethereum/eth-go/ethrpc" + "github.com/ethereum/eth-go/ethutil" + "io" + "log" + "os" + "os/signal" + "path" + "strings" + "time" ) var logger = ethlog.NewLogger("CLI") @@ -22,142 +22,142 @@ var interruptCallbacks = []func(os.Signal){} // Register interrupt handlers callbacks func RegisterInterrupt(cb func(os.Signal)) { - interruptCallbacks = append(interruptCallbacks, cb) + interruptCallbacks = append(interruptCallbacks, cb) } // go routine that call interrupt handlers in order of registering func HandleInterrupt() { - c := make(chan os.Signal, 1) - go func() { - signal.Notify(c, os.Interrupt) - for sig := range c { - logger.Errorf("Shutting down (%v) ... \n", sig) - RunInterruptCallbacks(sig) - } - }() + c := make(chan os.Signal, 1) + go func() { + signal.Notify(c, os.Interrupt) + for sig := range c { + logger.Errorf("Shutting down (%v) ... \n", sig) + RunInterruptCallbacks(sig) + } + }() } func RunInterruptCallbacks(sig os.Signal) { - for _, cb := range interruptCallbacks { - cb(sig) - } + for _, cb := range interruptCallbacks { + cb(sig) + } } func AbsolutePath(Datadir string, filename string) string { - if path.IsAbs(filename) { - return filename - } - return path.Join(Datadir, filename) -} - -func openLogFile (Datadir string, filename string) *os.File { - path := 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)) - } - return file -} - -func confirm (message string) bool { - fmt.Println(message, "Are you sure? (y/n)") - var r string - fmt.Scanln(&r) - for ; ; fmt.Scanln(&r) { - if r == "n" || r == "y" { - break - } else { - fmt.Printf("Yes or no?", r) - } - } - return r == "y" + if path.IsAbs(filename) { + return filename + } + return path.Join(Datadir, filename) +} + +func openLogFile(Datadir string, filename string) *os.File { + path := 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)) + } + return file +} + +func confirm(message string) bool { + fmt.Println(message, "Are you sure? (y/n)") + var r string + fmt.Scanln(&r) + for ; ; fmt.Scanln(&r) { + if r == "n" || r == "y" { + break + } else { + fmt.Printf("Yes or no?", r) + } + } + return r == "y" } func InitDataDir(Datadir string) { - _, err := os.Stat(Datadir) - if err != nil { - if os.IsNotExist(err) { - fmt.Printf("Debug logging directory '%s' doesn't exist, creating it\n", Datadir) - os.Mkdir(Datadir, 0777) - } - } -} - -func InitLogging (Datadir string, LogFile string, LogLevel int, DebugFile string) { - var writer io.Writer - if LogFile == "" { - writer = os.Stdout - } else { - writer = openLogFile(Datadir, LogFile) - } - ethlog.AddLogSystem(ethlog.NewStdLogSystem(writer, log.LstdFlags, ethlog.LogLevel(LogLevel))) - if DebugFile != "" { - writer = openLogFile(Datadir, DebugFile) - ethlog.AddLogSystem(ethlog.NewStdLogSystem(writer, log.LstdFlags, ethlog.DebugLevel)) - } + _, err := os.Stat(Datadir) + if err != nil { + if os.IsNotExist(err) { + fmt.Printf("Debug logging directory '%s' doesn't exist, creating it\n", Datadir) + os.Mkdir(Datadir, 0777) + } + } +} + +func InitLogging(Datadir string, LogFile string, LogLevel int, DebugFile string) { + var writer io.Writer + if LogFile == "" { + writer = os.Stdout + } else { + writer = openLogFile(Datadir, LogFile) + } + ethlog.AddLogSystem(ethlog.NewStdLogSystem(writer, log.LstdFlags, ethlog.LogLevel(LogLevel))) + if DebugFile != "" { + writer = openLogFile(Datadir, DebugFile) + ethlog.AddLogSystem(ethlog.NewStdLogSystem(writer, log.LstdFlags, ethlog.DebugLevel)) + } } func InitConfig(ConfigFile string, Datadir string, Identifier string, EnvPrefix string) { - InitDataDir(Datadir) - ethutil.ReadConfig(ConfigFile, Datadir, Identifier, EnvPrefix) - ethutil.Config.Set("rpcport", "700") + InitDataDir(Datadir) + ethutil.ReadConfig(ConfigFile, Datadir, Identifier, EnvPrefix) + ethutil.Config.Set("rpcport", "700") } func exit(status int) { - ethlog.Flush() - os.Exit(status) + ethlog.Flush() + os.Exit(status) } func NewEthereum(UseUPnP bool, OutboundPort string, MaxPeer int) *eth.Ethereum { - ethereum, err := eth.New(eth.CapDefault, UseUPnP) - if err != nil { - logger.Fatalln("eth start err:", err) - } - ethereum.Port = OutboundPort - ethereum.MaxPeers = MaxPeer - return ethereum + ethereum, err := eth.New(eth.CapDefault, UseUPnP) + if err != nil { + logger.Fatalln("eth start err:", err) + } + ethereum.Port = OutboundPort + ethereum.MaxPeers = MaxPeer + return ethereum } func StartEthereum(ethereum *eth.Ethereum, UseSeed bool) { - logger.Infof("Starting Ethereum v%s", ethutil.Config.Ver) - ethereum.Start(UseSeed) - RegisterInterrupt(func(sig os.Signal) { - ethereum.Stop() - ethlog.Flush() - }) + logger.Infof("Starting Ethereum v%s", ethutil.Config.Ver) + ethereum.Start(UseSeed) + RegisterInterrupt(func(sig os.Signal) { + ethereum.Stop() + ethlog.Flush() + }) } func ShowGenesis(ethereum *eth.Ethereum) { - logger.Infoln(ethereum.BlockChain().Genesis()) - exit(0) + logger.Infoln(ethereum.BlockChain().Genesis()) + exit(0) } func KeyTasks(GenAddr bool, ImportKey string, ExportKey bool, NonInteractive bool) { - switch { - case GenAddr: - if NonInteractive || confirm("This action overwrites your old private key.") { - CreateKeyPair(true) - } - exit(0) - case len(ImportKey) > 0: - if NonInteractive || confirm("This action overwrites your old private key.") { - // import should be from file - mnemonic := strings.Split(ImportKey, " ") - if len(mnemonic) == 24 { - logger.Infoln("Got mnemonic key, importing.") - key := ethutil.MnemonicDecode(mnemonic) - ImportPrivateKey(key) - } else if len(mnemonic) == 1 { - logger.Infoln("Got hex key, importing.") - ImportPrivateKey(ImportKey) - } else { - logger.Errorln("Did not recognise format, exiting.") - } - } - exit(0) - case ExportKey: // this should be exporting to a filename - keyPair := ethutil.GetKeyRing().Get(0) - fmt.Printf(` + switch { + case GenAddr: + if NonInteractive || confirm("This action overwrites your old private key.") { + CreateKeyPair(true) + } + exit(0) + case len(ImportKey) > 0: + if NonInteractive || confirm("This action overwrites your old private key.") { + // import should be from file + mnemonic := strings.Split(ImportKey, " ") + if len(mnemonic) == 24 { + logger.Infoln("Got mnemonic key, importing.") + key := ethutil.MnemonicDecode(mnemonic) + ImportPrivateKey(key) + } else if len(mnemonic) == 1 { + logger.Infoln("Got hex key, importing.") + ImportPrivateKey(ImportKey) + } else { + logger.Errorln("Did not recognise format, exiting.") + } + } + exit(0) + case ExportKey: // this should be exporting to a filename + keyPair := ethutil.GetKeyRing().Get(0) + fmt.Printf(` Generating new address and keypair. Please keep your keys somewhere save. @@ -169,61 +169,61 @@ pubk: %x save these words so you can restore your account later: %s `, keyPair.Address(), keyPair.PrivateKey, keyPair.PublicKey) - exit(0) - default: - // Creates a keypair if none exists - CreateKeyPair(false) - } + exit(0) + default: + // Creates a keypair if none exists + CreateKeyPair(false) + } } func StartRpc(ethereum *eth.Ethereum, RpcPort int) { - var err error - ethereum.RpcServer, err = ethrpc.NewJsonRpcServer(ethpub.NewPEthereum(ethereum), RpcPort) - if err != nil { - logger.Errorf("Could not start RPC interface (port %v): %v", RpcPort, err) - } else { - go ethereum.RpcServer.Start() - } + var err error + ethereum.RpcServer, err = ethrpc.NewJsonRpcServer(ethpub.NewPEthereum(ethereum), RpcPort) + if err != nil { + logger.Errorf("Could not start RPC interface (port %v): %v", RpcPort, err) + } else { + go ethereum.RpcServer.Start() + } } var miner ethminer.Miner func StartMining(ethereum *eth.Ethereum) bool { - if !ethereum.Mining { - ethereum.Mining = true - - if ethutil.GetKeyRing().Len() == 0 { - logger.Errorln("No address found, can't start mining") - ethereum.Mining = false - return true //???? - } - keyPair := ethutil.GetKeyRing().Get(0) - addr := keyPair.Address() - - go func() { - miner = ethminer.NewDefaultMiner(addr, ethereum) - // Give it some time to connect with peers - time.Sleep(3 * time.Second) - logger.Infoln("Miner started") - miner := ethminer.NewDefaultMiner(addr, ethereum) - miner.Start() - }() - RegisterInterrupt(func(os.Signal) { - StopMining(ethereum) - }) - return true - } - return false + if !ethereum.Mining { + ethereum.Mining = true + + if ethutil.GetKeyRing().Len() == 0 { + logger.Errorln("No address found, can't start mining") + ethereum.Mining = false + return true //???? + } + keyPair := ethutil.GetKeyRing().Get(0) + addr := keyPair.Address() + + go func() { + miner = ethminer.NewDefaultMiner(addr, ethereum) + // Give it some time to connect with peers + time.Sleep(3 * time.Second) + logger.Infoln("Miner started") + miner := ethminer.NewDefaultMiner(addr, ethereum) + miner.Start() + }() + RegisterInterrupt(func(os.Signal) { + StopMining(ethereum) + }) + return true + } + return false } func StopMining(ethereum *eth.Ethereum) bool { - if ethereum.Mining { - miner.Stop() - logger.Infoln("Miner stopped") - ethereum.Mining = false - return true - } - return false + if ethereum.Mining { + miner.Stop() + logger.Infoln("Miner stopped") + ethereum.Mining = false + return true + } + return false } // Replay block -- cgit v1.2.3 From 4fc60f340f6ef5ffe68e684ed44e5974fa08e8c8 Mon Sep 17 00:00:00 2001 From: obscuren Date: Sun, 29 Jun 2014 10:43:56 +0200 Subject: Wait for catchup when starting the miner --- utils/cmd.go | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'utils') diff --git a/utils/cmd.go b/utils/cmd.go index c084542b4..1d97c9639 100644 --- a/utils/cmd.go +++ b/utils/cmd.go @@ -204,6 +204,10 @@ func StartMining(ethereum *eth.Ethereum) bool { miner = ethminer.NewDefaultMiner(addr, ethereum) // Give it some time to connect with peers time.Sleep(3 * time.Second) + for !ethereum.IsUpToDate() == false { + time.Sleep(5 * time.Second) + } + logger.Infoln("Miner started") miner := ethminer.NewDefaultMiner(addr, ethereum) miner.Start() -- cgit v1.2.3 From 2d48fc11130d5aba8ed9f37ecdf7f8b5115753cf Mon Sep 17 00:00:00 2001 From: zelig Date: Sun, 29 Jun 2014 13:43:27 +0100 Subject: fix logmessage if data directory doesn't exist --- utils/cmd.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'utils') diff --git a/utils/cmd.go b/utils/cmd.go index c084542b4..99a1f2628 100644 --- a/utils/cmd.go +++ b/utils/cmd.go @@ -77,7 +77,7 @@ func InitDataDir(Datadir string) { _, err := os.Stat(Datadir) if err != nil { if os.IsNotExist(err) { - fmt.Printf("Debug logging directory '%s' doesn't exist, creating it\n", Datadir) + fmt.Printf("Data directory '%s' doesn't exist, creating it\n", Datadir) os.Mkdir(Datadir, 0777) } } -- cgit v1.2.3 From 9bd67de671bd0f70e85dcc518fd91fa080a849fc Mon Sep 17 00:00:00 2001 From: zelig Date: Sun, 29 Jun 2014 18:38:17 +0100 Subject: remove keys file, now subsumed under ethcrypto/key_manager --- utils/keys.go | 108 ---------------------------------------------------------- 1 file changed, 108 deletions(-) delete mode 100644 utils/keys.go (limited to 'utils') diff --git a/utils/keys.go b/utils/keys.go deleted file mode 100644 index 1c0f6a9d6..000000000 --- a/utils/keys.go +++ /dev/null @@ -1,108 +0,0 @@ -package utils - -import ( - "fmt" - "github.com/ethereum/eth-go/ethutil" - "github.com/obscuren/secp256k1-go" -) - -func CreateKeyPair(force bool) { - if force { - ethutil.GetKeyRing().Reset() - fmt.Println("resetting") - } - - if ethutil.GetKeyRing().Get(0) == nil { - _, prv := secp256k1.GenerateKeyPair() - - keyPair, err := ethutil.GetKeyRing().NewKeyPair(prv) - if err != nil { - panic(err) - } - - mne := ethutil.MnemonicEncode(ethutil.Hex(keyPair.PrivateKey)) - - fmt.Printf(` -Generating new address and keypair. -Please keep your keys somewhere save. - -++++++++++++++++ KeyRing +++++++++++++++++++ -addr: %x -prvk: %x -pubk: %x -++++++++++++++++++++++++++++++++++++++++++++ -save these words so you can restore your account later: %s -`, keyPair.Address(), keyPair.PrivateKey, keyPair.PublicKey, mne) - } -} - -func ImportPrivateKey(sec string) { - ethutil.GetKeyRing().Reset() - - keyPair, err := ethutil.GetKeyRing().NewKeyPair(ethutil.FromHex(sec)) - if err != nil { - panic(err) - } - - mne := ethutil.MnemonicEncode(ethutil.Hex(keyPair.PrivateKey)) - - fmt.Printf(` -Generating new address and keypair. -Please keep your keys somewhere save. - -++++++++++++++++ KeyRing +++++++++++++++++++ -addr: %x -prvk: %x -pubk: %x -++++++++++++++++++++++++++++++++++++++++++++ -save these words so you can restore your account later: %s -`, keyPair.Address(), keyPair.PrivateKey, keyPair.PublicKey, mne) -} - -/* -func CreateKeyPair(force bool) { - data, _ := ethutil.Config.Db.Get([]byte("KeyRing")) - if len(data) == 0 || force { - pub, prv := secp256k1.GenerateKeyPair() - pair := ðutil.Key{PrivateKey: prv, PublicKey: pub} - ethutil.Config.Db.Put([]byte("KeyRing"), pair.RlpEncode()) - mne := ethutil.MnemonicEncode(ethutil.Hex(prv)) - - fmt.Printf(` -Generating new address and keypair. -Please keep your keys somewhere save. - -++++++++++++++++ KeyRing +++++++++++++++++++ -addr: %x -prvk: %x -pubk: %x -++++++++++++++++++++++++++++++++++++++++++++ -save these words so you can restore your account later: %s -`, pair.Address(), prv, pub, mne) - - } -} -*/ - -/* -func ImportPrivateKey(prvKey string) { - key := ethutil.FromHex(prvKey) - msg := []byte("tmp") - // Couldn't think of a better way to get the pub key - sig, _ := secp256k1.Sign(msg, key) - pub, _ := secp256k1.RecoverPubkey(msg, sig) - pair := ðutil.Key{PrivateKey: key, PublicKey: pub} - ethutil.Config.Db.Put([]byte("KeyRing"), pair.RlpEncode()) - - fmt.Printf(` -Importing private key - -++++++++++++++++ KeyRing +++++++++++++++++++ -addr: %x -prvk: %x -pubk: %x -++++++++++++++++++++++++++++++++++++++++++++ - -`, pair.Address(), key, pub) -} -*/ -- cgit v1.2.3 From cf7fcadeca356adf780d00583a16f0b722cc7987 Mon Sep 17 00:00:00 2001 From: zelig Date: Sun, 29 Jun 2014 18:39:13 +0100 Subject: added utility functions to set up db, keymanager, ethereum init and simplify key tasks --- utils/cmd.go | 96 +++++++++++++++++++++++++++++++----------------------------- 1 file changed, 50 insertions(+), 46 deletions(-) (limited to 'utils') diff --git a/utils/cmd.go b/utils/cmd.go index 99a1f2628..d20af98cc 100644 --- a/utils/cmd.go +++ b/utils/cmd.go @@ -3,6 +3,8 @@ package utils import ( "fmt" "github.com/ethereum/eth-go" + "github.com/ethereum/eth-go/ethcrypto" + "github.com/ethereum/eth-go/ethdb" "github.com/ethereum/eth-go/ethlog" "github.com/ethereum/eth-go/ethminer" "github.com/ethereum/eth-go/ethpub" @@ -13,7 +15,6 @@ import ( "os" "os/signal" "path" - "strings" "time" ) @@ -100,16 +101,28 @@ func InitLogging(Datadir string, LogFile string, LogLevel int, DebugFile string) func InitConfig(ConfigFile string, Datadir string, Identifier string, EnvPrefix string) { InitDataDir(Datadir) ethutil.ReadConfig(ConfigFile, Datadir, Identifier, EnvPrefix) - ethutil.Config.Set("rpcport", "700") } -func exit(status int) { +func exit(err error) { + status := 0 + if err != nil { + logger.Errorln("Fatal: ", err) + status = 1 + } ethlog.Flush() os.Exit(status) } -func NewEthereum(UseUPnP bool, OutboundPort string, MaxPeer int) *eth.Ethereum { - ethereum, err := eth.New(eth.CapDefault, UseUPnP) +func NewDatabase() ethutil.Database { + db, err := ethdb.NewLDBDatabase("database") + if err != nil { + exit(err) + } + return db +} + +func NewEthereum(db ethutil.Database, keyManager *ethcrypto.KeyManager, usePnp bool, OutboundPort string, MaxPeer int) *eth.Ethereum { + ethereum, err := eth.New(db, keyManager, eth.CapDefault, usePnp) if err != nil { logger.Fatalln("eth start err:", err) } @@ -129,50 +142,47 @@ func StartEthereum(ethereum *eth.Ethereum, UseSeed bool) { func ShowGenesis(ethereum *eth.Ethereum) { logger.Infoln(ethereum.BlockChain().Genesis()) - exit(0) + exit(nil) } -func KeyTasks(GenAddr bool, ImportKey string, ExportKey bool, NonInteractive bool) { +func NewKeyManager(KeyStore string, Datadir string, db ethutil.Database) *ethcrypto.KeyManager { + var keyManager *ethcrypto.KeyManager + switch { + case KeyStore == "db": + keyManager = ethcrypto.NewDBKeyManager(db) + case KeyStore == "file": + keyManager = ethcrypto.NewFileKeyManager(Datadir) + default: + exit(fmt.Errorf("unknown keystore type: %s", KeyStore)) + } + return keyManager +} + +func KeyTasks(keyManager *ethcrypto.KeyManager, KeyRing string, GenAddr bool, SecretFile string, ExportDir string, NonInteractive bool) { + var err error switch { case GenAddr: if NonInteractive || confirm("This action overwrites your old private key.") { - CreateKeyPair(true) + err = keyManager.Init(KeyRing, 0, true) } - exit(0) - case len(ImportKey) > 0: + exit(err) + case len(SecretFile) > 0: if NonInteractive || confirm("This action overwrites your old private key.") { - // import should be from file - mnemonic := strings.Split(ImportKey, " ") - if len(mnemonic) == 24 { - logger.Infoln("Got mnemonic key, importing.") - key := ethutil.MnemonicDecode(mnemonic) - ImportPrivateKey(key) - } else if len(mnemonic) == 1 { - logger.Infoln("Got hex key, importing.") - ImportPrivateKey(ImportKey) - } else { - logger.Errorln("Did not recognise format, exiting.") - } + err = keyManager.InitFromSecretsFile(KeyRing, 0, SecretFile) } - exit(0) - case ExportKey: // this should be exporting to a filename - keyPair := ethutil.GetKeyRing().Get(0) - fmt.Printf(` -Generating new address and keypair. -Please keep your keys somewhere save. - -++++++++++++++++ KeyRing +++++++++++++++++++ -addr: %x -prvk: %x -pubk: %x -++++++++++++++++++++++++++++++++++++++++++++ -save these words so you can restore your account later: %s -`, keyPair.Address(), keyPair.PrivateKey, keyPair.PublicKey) - - exit(0) + exit(err) + case len(ExportDir) > 0: + err = keyManager.Init(KeyRing, 0, false) + if err == nil { + err = keyManager.Export(ExportDir) + } + exit(err) default: // Creates a keypair if none exists - CreateKeyPair(false) + err = keyManager.Init(KeyRing, 0, false) + if err != nil { + exit(err) + } } } @@ -192,13 +202,7 @@ func StartMining(ethereum *eth.Ethereum) bool { if !ethereum.Mining { ethereum.Mining = true - if ethutil.GetKeyRing().Len() == 0 { - logger.Errorln("No address found, can't start mining") - ethereum.Mining = false - return true //???? - } - keyPair := ethutil.GetKeyRing().Get(0) - addr := keyPair.Address() + addr := ethereum.KeyManager().Address() go func() { miner = ethminer.NewDefaultMiner(addr, ethereum) -- cgit v1.2.3