From 642630db15a793cf0a0f7fbd827daee364df5423 Mon Sep 17 00:00:00 2001 From: obscuren Date: Sat, 22 Mar 2014 12:03:10 +0100 Subject: Moved node to ethereum --- ethereum/config.go | 37 +++++++ ethereum/dev_console.go | 253 ++++++++++++++++++++++++++++++++++++++++++++++++ ethereum/ethereum.go | 158 ++++++++++++++++++++++++++++++ 3 files changed, 448 insertions(+) create mode 100644 ethereum/config.go create mode 100644 ethereum/dev_console.go create mode 100644 ethereum/ethereum.go (limited to 'ethereum') diff --git a/ethereum/config.go b/ethereum/config.go new file mode 100644 index 000000000..e4935dfed --- /dev/null +++ b/ethereum/config.go @@ -0,0 +1,37 @@ +package main + +import ( + "flag" +) + +var StartConsole bool +var StartMining bool +var UseUPnP bool +var OutboundPort string +var ShowGenesis bool +var AddPeer string +var MaxPeer int +var GenAddr bool +var UseSeed bool +var ImportKey string +var ExportKey bool + +//var UseGui bool +var DataDir string + +func Init() { + flag.BoolVar(&StartConsole, "c", false, "debug and testing console") + flag.BoolVar(&StartMining, "m", false, "start dagger mining") + flag.BoolVar(&ShowGenesis, "g", false, "prints genesis header and exits") + //flag.BoolVar(&UseGui, "gui", true, "use the gui") + flag.BoolVar(&UseUPnP, "upnp", false, "enable UPnP support") + flag.BoolVar(&UseSeed, "seed", true, "seed peers") + flag.BoolVar(&GenAddr, "genaddr", false, "create a new priv/pub key") + flag.BoolVar(&ExportKey, "export", false, "export private key") + flag.StringVar(&OutboundPort, "p", "30303", "listening port") + flag.StringVar(&DataDir, "dir", ".ethereum", "ethereum data directory") + flag.StringVar(&ImportKey, "import", "", "imports the given private key (hex)") + flag.IntVar(&MaxPeer, "x", 5, "maximum desired peers") + + flag.Parse() +} diff --git a/ethereum/dev_console.go b/ethereum/dev_console.go new file mode 100644 index 000000000..ead4b55e5 --- /dev/null +++ b/ethereum/dev_console.go @@ -0,0 +1,253 @@ +package main + +import ( + "bufio" + "bytes" + "encoding/hex" + "errors" + "fmt" + "github.com/ethereum/eth-go" + "github.com/ethereum/eth-go/ethchain" + "github.com/ethereum/eth-go/ethdb" + "github.com/ethereum/eth-go/ethutil" + "github.com/ethereum/eth-go/ethwire" + _ "math/big" + "os" + "strings" +) + +type Console struct { + db *ethdb.MemDatabase + trie *ethutil.Trie + ethereum *eth.Ethereum +} + +func NewConsole(s *eth.Ethereum) *Console { + db, _ := ethdb.NewMemDatabase() + trie := ethutil.NewTrie(db, "") + + return &Console{db: db, trie: trie, ethereum: s} +} + +func (i *Console) ValidateInput(action string, argumentLength int) error { + err := false + var expArgCount int + + switch { + case action == "update" && argumentLength != 2: + err = true + expArgCount = 2 + case action == "get" && argumentLength != 1: + err = true + expArgCount = 1 + case action == "dag" && argumentLength != 2: + err = true + expArgCount = 2 + case action == "decode" && argumentLength != 1: + err = true + expArgCount = 1 + case action == "encode" && argumentLength != 1: + err = true + expArgCount = 1 + case action == "gettx" && argumentLength != 1: + err = true + expArgCount = 1 + case action == "tx" && argumentLength != 2: + err = true + expArgCount = 2 + case action == "getaddr" && argumentLength != 1: + err = true + expArgCount = 1 + case action == "contract" && argumentLength != 1: + err = true + expArgCount = 1 + case action == "say" && argumentLength != 1: + err = true + expArgCount = 1 + case action == "addp" && argumentLength != 1: + err = true + expArgCount = 1 + case action == "block" && argumentLength != 1: + err = true + expArgCount = 1 + } + + if err { + return errors.New(fmt.Sprintf("'%s' requires %d args, got %d", action, expArgCount, argumentLength)) + } else { + return nil + } +} + +func (i *Console) Editor() []string { + var buff bytes.Buffer + for { + reader := bufio.NewReader(os.Stdin) + str, _, err := reader.ReadLine() + if len(str) > 0 { + buff.Write(str) + buff.WriteString("\n") + } + + if err != nil && err.Error() == "EOF" { + break + } + } + + scanner := bufio.NewScanner(strings.NewReader(buff.String())) + scanner.Split(bufio.ScanLines) + + var lines []string + for scanner.Scan() { + lines = append(lines, scanner.Text()) + } + + return lines +} + +func (i *Console) PrintRoot() { + root := ethutil.NewValue(i.trie.Root) + if len(root.Bytes()) != 0 { + fmt.Println(hex.EncodeToString(root.Bytes())) + } else { + fmt.Println(i.trie.Root) + } +} + +func (i *Console) ParseInput(input string) bool { + scanner := bufio.NewScanner(strings.NewReader(input)) + scanner.Split(bufio.ScanWords) + + count := 0 + var tokens []string + for scanner.Scan() { + count++ + tokens = append(tokens, scanner.Text()) + } + if err := scanner.Err(); err != nil { + fmt.Fprintln(os.Stderr, "reading input:", err) + } + + if len(tokens) == 0 { + return true + } + + err := i.ValidateInput(tokens[0], count-1) + if err != nil { + fmt.Println(err) + } else { + switch tokens[0] { + case "update": + i.trie.Update(tokens[1], tokens[2]) + + i.PrintRoot() + case "get": + fmt.Println(i.trie.Get(tokens[1])) + case "root": + i.PrintRoot() + case "rawroot": + fmt.Println(i.trie.Root) + case "print": + i.db.Print() + case "dag": + fmt.Println(ethchain.DaggerVerify(ethutil.Big(tokens[1]), // hash + ethutil.BigPow(2, 36), // diff + ethutil.Big(tokens[2]))) // nonce + case "decode": + value := ethutil.NewValueFromBytes([]byte(tokens[1])) + fmt.Println(value) + case "getaddr": + encoded, _ := hex.DecodeString(tokens[1]) + addr := i.ethereum.BlockChain().CurrentBlock.State().GetAccount(encoded) + fmt.Println("addr:", addr) + case "block": + encoded, _ := hex.DecodeString(tokens[1]) + block := i.ethereum.BlockChain().GetBlock(encoded) + info := block.BlockInfo() + fmt.Printf("++++++++++ #%d ++++++++++\n%v\n", info.Number, block) + case "say": + i.ethereum.Broadcast(ethwire.MsgTalkTy, []interface{}{tokens[1]}) + case "addp": + i.ethereum.ConnectToPeer(tokens[1]) + case "pcount": + fmt.Println("peers:", i.ethereum.Peers().Len()) + case "encode": + fmt.Printf("%q\n", ethutil.Encode(tokens[1])) + case "tx": + recipient, err := hex.DecodeString(tokens[1]) + if err != nil { + fmt.Println("recipient err:", err) + } else { + tx := ethchain.NewTransaction(recipient, ethutil.Big(tokens[2]), []string{""}) + + key := ethutil.Config.Db.GetKeys()[0] + tx.Sign(key.PrivateKey) + i.ethereum.TxPool().QueueTransaction(tx) + + fmt.Printf("%x\n", tx.Hash()) + } + case "gettx": + addr, _ := hex.DecodeString(tokens[1]) + data, _ := ethutil.Config.Db.Get(addr) + if len(data) != 0 { + decoder := ethutil.NewValueFromBytes(data) + fmt.Println(decoder) + } else { + fmt.Println("gettx: tx not found") + } + case "contract": + fmt.Println("Contract editor (Ctrl-D = done)") + code := ethchain.Compile(i.Editor()) + + contract := ethchain.NewTransaction(ethchain.ContractAddr, ethutil.Big(tokens[1]), code) + + key := ethutil.Config.Db.GetKeys()[0] + contract.Sign(key.PrivateKey) + + i.ethereum.TxPool().QueueTransaction(contract) + + fmt.Printf("%x\n", contract.Hash()[12:]) + case "exit", "quit", "q": + return false + case "help": + fmt.Printf("COMMANDS:\n" + + "\033[1m= DB =\033[0m\n" + + "update KEY VALUE - Updates/Creates a new value for the given key\n" + + "get KEY - Retrieves the given key\n" + + "root - Prints the hex encoded merkle root\n" + + "rawroot - Prints the raw merkle root\n" + + "block HASH - Prints the block\n" + + "getaddr ADDR - Prints the account associated with the address\n" + + "\033[1m= Dagger =\033[0m\n" + + "dag HASH NONCE - Verifies a nonce with the given hash with dagger\n" + + "\033[1m= Encoding =\033[0m\n" + + "decode STR\n" + + "encode STR\n" + + "\033[1m= Other =\033[0m\n" + + "addp HOST:PORT\n" + + "tx TO AMOUNT\n" + + "contract AMOUNT\n") + + default: + fmt.Println("Unknown command:", tokens[0]) + } + } + + return true +} + +func (i *Console) Start() { + fmt.Printf("Eth Console. Type (help) for help\n") + reader := bufio.NewReader(os.Stdin) + for { + fmt.Printf("eth >>> ") + str, _, err := reader.ReadLine() + if err != nil { + fmt.Println("Error reading input", err) + } else { + if !i.ParseInput(string(str)) { + return + } + } + } +} diff --git a/ethereum/ethereum.go b/ethereum/ethereum.go new file mode 100644 index 000000000..3f5e4a8f5 --- /dev/null +++ b/ethereum/ethereum.go @@ -0,0 +1,158 @@ +package main + +import ( + "fmt" + "github.com/ethereum/eth-go" + "github.com/ethereum/eth-go/ethchain" + "github.com/ethereum/eth-go/ethutil" + "github.com/ethereum/eth-go/ethwire" + "github.com/ethereum/go-ethereum/utils" + "log" + "os" + "os/signal" + "runtime" +) + +const Debug = true + +// Register interrupt handlers so we can stop the ethereum +func RegisterInterupts(s *eth.Ethereum) { + // Buffered chan of one is enough + c := make(chan os.Signal, 1) + // Notify about interrupts for now + signal.Notify(c, os.Interrupt) + go func() { + for sig := range c { + fmt.Printf("Shutting down (%v) ... \n", sig) + + s.Stop() + } + }() +} + +func main() { + Init() + + runtime.GOMAXPROCS(runtime.NumCPU()) + + ethchain.InitFees() + ethutil.ReadConfig(DataDir) + ethutil.Config.Seed = UseSeed + + // Instantiated a eth stack + ethereum, err := eth.New(eth.CapDefault, UseUPnP) + if err != nil { + log.Println("eth start err:", err) + return + } + ethereum.Port = OutboundPort + + if GenAddr { + fmt.Println("This action overwrites your old private key. 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) + } + } + + if r == "y" { + utils.CreateKeyPair(true) + } + os.Exit(0) + } else { + if len(ImportKey) > 0 { + fmt.Println("This action overwrites your old private key. 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) + } + } + + if r == "y" { + utils.ImportPrivateKey(ImportKey) + os.Exit(0) + } + } else { + utils.CreateKeyPair(false) + } + } + + if ExportKey { + key := ethutil.Config.Db.GetKeys()[0] + fmt.Printf("%x\n", key.PrivateKey) + os.Exit(0) + } + + if ShowGenesis { + fmt.Println(ethereum.BlockChain().Genesis()) + os.Exit(0) + } + + log.Printf("Starting Ethereum v%s\n", ethutil.Config.Ver) + + // Set the max peers + ethereum.MaxPeers = MaxPeer + + if StartConsole { + err := os.Mkdir(ethutil.Config.ExecPath, os.ModePerm) + // Error is OK if the error is ErrExist + if err != nil && !os.IsExist(err) { + log.Panic("Unable to create EXECPATH:", err) + } + + console := NewConsole(ethereum) + go console.Start() + } + + RegisterInterupts(ethereum) + ethereum.Start() + + if StartMining { + log.Printf("Miner started\n") + + // Fake block mining. It broadcasts a new block every 5 seconds + go func() { + pow := ðchain.EasyPow{} + data, _ := ethutil.Config.Db.Get([]byte("KeyRing")) + keyRing := ethutil.NewValueFromBytes(data) + addr := keyRing.Get(1).Bytes() + + for { + txs := ethereum.TxPool().Flush() + // Create a new block which we're going to mine + block := ethereum.BlockChain().NewBlock(addr, txs) + log.Println("Mining on new block. Includes", len(block.Transactions()), "transactions") + // Apply all transactions to the block + ethereum.StateManager().ApplyTransactions(block, block.Transactions()) + + ethereum.StateManager().Prepare(block.State(), block.State()) + ethereum.StateManager().AccumelateRewards(block) + + // Search the nonce + block.Nonce = pow.Search(block) + ethereum.Broadcast(ethwire.MsgBlockTy, []interface{}{block.Value().Val}) + + ethereum.StateManager().PrepareDefault(block) + err := ethereum.StateManager().ProcessBlock(block) + if err != nil { + log.Println(err) + } else { + log.Println("\n+++++++ MINED BLK +++++++\n", ethereum.BlockChain().CurrentBlock) + log.Printf("🔨 Mined block %x\n", block.Hash()) + } + } + }() + } + + // Wait for shutdown + ethereum.WaitForShutdown() +} -- cgit v1.2.3 From a30f5730b384bf99d23f6e83b356e27a14f961d1 Mon Sep 17 00:00:00 2001 From: Maran Date: Mon, 24 Mar 2014 10:56:42 +0100 Subject: Reimplement new miner creation --- ethereum/ethereum.go | 44 +++++++++++++++----------------------------- 1 file changed, 15 insertions(+), 29 deletions(-) (limited to 'ethereum') diff --git a/ethereum/ethereum.go b/ethereum/ethereum.go index 3f5e4a8f5..c82e7dcd8 100644 --- a/ethereum/ethereum.go +++ b/ethereum/ethereum.go @@ -4,8 +4,8 @@ import ( "fmt" "github.com/ethereum/eth-go" "github.com/ethereum/eth-go/ethchain" + "github.com/ethereum/eth-go/ethminer" "github.com/ethereum/eth-go/ethutil" - "github.com/ethereum/eth-go/ethwire" "github.com/ethereum/go-ethereum/utils" "log" "os" @@ -121,36 +121,22 @@ func main() { // Fake block mining. It broadcasts a new block every 5 seconds go func() { - pow := ðchain.EasyPow{} - data, _ := ethutil.Config.Db.Get([]byte("KeyRing")) - keyRing := ethutil.NewValueFromBytes(data) - addr := keyRing.Get(1).Bytes() - - for { - txs := ethereum.TxPool().Flush() - // Create a new block which we're going to mine - block := ethereum.BlockChain().NewBlock(addr, txs) - log.Println("Mining on new block. Includes", len(block.Transactions()), "transactions") - // Apply all transactions to the block - ethereum.StateManager().ApplyTransactions(block, block.Transactions()) - - ethereum.StateManager().Prepare(block.State(), block.State()) - ethereum.StateManager().AccumelateRewards(block) - - // Search the nonce - block.Nonce = pow.Search(block) - ethereum.Broadcast(ethwire.MsgBlockTy, []interface{}{block.Value().Val}) - - ethereum.StateManager().PrepareDefault(block) - err := ethereum.StateManager().ProcessBlock(block) - if err != nil { - log.Println(err) - } else { - log.Println("\n+++++++ MINED BLK +++++++\n", ethereum.BlockChain().CurrentBlock) - log.Printf("🔨 Mined block %x\n", block.Hash()) - } + + if StartMining { + log.Printf("Miner started\n") + + go func() { + data, _ := ethutil.Config.Db.Get([]byte("KeyRing")) + keyRing := ethutil.NewValueFromBytes(data) + addr := keyRing.Get(1).Bytes() + + miner := ethminer.NewDefaultMiner(addr, ethereum) + miner.Start() + + }() } }() + } // Wait for shutdown -- cgit v1.2.3 From e65c4ee93e9dad629997c7839df7a8a0e7cff353 Mon Sep 17 00:00:00 2001 From: obscuren Date: Thu, 27 Mar 2014 15:22:20 +0100 Subject: Updated transaction constructor --- ethereum/dev_console.go | 25 ++++++++++--------------- 1 file changed, 10 insertions(+), 15 deletions(-) (limited to 'ethereum') diff --git a/ethereum/dev_console.go b/ethereum/dev_console.go index ead4b55e5..5452b9a61 100644 --- a/ethereum/dev_console.go +++ b/ethereum/dev_console.go @@ -11,6 +11,7 @@ import ( "github.com/ethereum/eth-go/ethdb" "github.com/ethereum/eth-go/ethutil" "github.com/ethereum/eth-go/ethwire" + "github.com/obscuren/mutan" _ "math/big" "os" "strings" @@ -58,9 +59,9 @@ func (i *Console) ValidateInput(action string, argumentLength int) error { case action == "getaddr" && argumentLength != 1: err = true expArgCount = 1 - case action == "contract" && argumentLength != 1: + case action == "contract" && argumentLength != 2: err = true - expArgCount = 1 + expArgCount = 2 case action == "say" && argumentLength != 1: err = true expArgCount = 1 @@ -79,7 +80,7 @@ func (i *Console) ValidateInput(action string, argumentLength int) error { } } -func (i *Console) Editor() []string { +func (i *Console) Editor() string { var buff bytes.Buffer for { reader := bufio.NewReader(os.Stdin) @@ -94,15 +95,7 @@ func (i *Console) Editor() []string { } } - scanner := bufio.NewScanner(strings.NewReader(buff.String())) - scanner.Split(bufio.ScanLines) - - var lines []string - for scanner.Scan() { - lines = append(lines, scanner.Text()) - } - - return lines + return buff.String() } func (i *Console) PrintRoot() { @@ -178,7 +171,7 @@ func (i *Console) ParseInput(input string) bool { if err != nil { fmt.Println("recipient err:", err) } else { - tx := ethchain.NewTransaction(recipient, ethutil.Big(tokens[2]), []string{""}) + tx := ethchain.NewTx(recipient, ethutil.Big(tokens[2]), []string{""}) key := ethutil.Config.Db.GetKeys()[0] tx.Sign(key.PrivateKey) @@ -197,9 +190,11 @@ func (i *Console) ParseInput(input string) bool { } case "contract": fmt.Println("Contract editor (Ctrl-D = done)") - code := ethchain.Compile(i.Editor()) + asm := mutan.NewCompiler().Compile(strings.NewReader(i.Editor())) + + code := ethutil.Assemble(asm) - contract := ethchain.NewTransaction(ethchain.ContractAddr, ethutil.Big(tokens[1]), code) + contract := ethchain.NewContractCreationTx(ethutil.Big(tokens[0]), ethutil.Big(tokens[1]), code) key := ethutil.Config.Db.GetKeys()[0] contract.Sign(key.PrivateKey) -- cgit v1.2.3 From c5215fd4fb9de7594fdb812f8f9e4c471ee8d003 Mon Sep 17 00:00:00 2001 From: obscuren Date: Thu, 27 Mar 2014 19:41:42 +0100 Subject: Added gas and gas price. * library's `createTx` method changed so it accepts a gas price * dev console accepts code as well as the library --- ethereum/dev_console.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'ethereum') diff --git a/ethereum/dev_console.go b/ethereum/dev_console.go index 5452b9a61..5fdf90509 100644 --- a/ethereum/dev_console.go +++ b/ethereum/dev_console.go @@ -190,7 +190,11 @@ func (i *Console) ParseInput(input string) bool { } case "contract": fmt.Println("Contract editor (Ctrl-D = done)") - asm := mutan.NewCompiler().Compile(strings.NewReader(i.Editor())) + asm, err := mutan.NewCompiler().Compile(strings.NewReader(i.Editor())) + if err != nil { + fmt.Println(err) + break + } code := ethutil.Assemble(asm) -- cgit v1.2.3 From 3fb7ae2fa19fede545466694fbf9d86a85310bd9 Mon Sep 17 00:00:00 2001 From: obscuren Date: Thu, 27 Mar 2014 19:45:55 +0100 Subject: Removed CreateTx --- ethereum/dev_console.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'ethereum') diff --git a/ethereum/dev_console.go b/ethereum/dev_console.go index 5fdf90509..ff25d694c 100644 --- a/ethereum/dev_console.go +++ b/ethereum/dev_console.go @@ -53,9 +53,9 @@ func (i *Console) ValidateInput(action string, argumentLength int) error { case action == "gettx" && argumentLength != 1: err = true expArgCount = 1 - case action == "tx" && argumentLength != 2: + case action == "tx" && argumentLength != 4: err = true - expArgCount = 2 + expArgCount = 4 case action == "getaddr" && argumentLength != 1: err = true expArgCount = 1 @@ -171,7 +171,7 @@ func (i *Console) ParseInput(input string) bool { if err != nil { fmt.Println("recipient err:", err) } else { - tx := ethchain.NewTx(recipient, ethutil.Big(tokens[2]), []string{""}) + tx := ethchain.NewTransactionMessage(recipient, ethutil.Big(tokens[2]), ethutil.Big(tokens[3]), ethutil.Big(tokens[4]), []string{""}) key := ethutil.Config.Db.GetKeys()[0] tx.Sign(key.PrivateKey) -- cgit v1.2.3 From ebbc5e7cb8b3886c8557f9f8623113f52f7f5e4a Mon Sep 17 00:00:00 2001 From: obscuren Date: Sun, 30 Mar 2014 22:03:29 +0200 Subject: Updated to new mutan api --- ethereum/dev_console.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'ethereum') diff --git a/ethereum/dev_console.go b/ethereum/dev_console.go index ff25d694c..421c3fa60 100644 --- a/ethereum/dev_console.go +++ b/ethereum/dev_console.go @@ -190,7 +190,7 @@ func (i *Console) ParseInput(input string) bool { } case "contract": fmt.Println("Contract editor (Ctrl-D = done)") - asm, err := mutan.NewCompiler().Compile(strings.NewReader(i.Editor())) + asm, err := mutan.Compile(strings.NewReader(i.Editor()), false) if err != nil { fmt.Println(err) break -- cgit v1.2.3 From e403b28eea6959c1d0ed003d955df3dee586083b Mon Sep 17 00:00:00 2001 From: obscuren Date: Mon, 31 Mar 2014 01:02:00 +0200 Subject: Fixed miner --- ethereum/ethereum.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'ethereum') diff --git a/ethereum/ethereum.go b/ethereum/ethereum.go index 3f5e4a8f5..666c75117 100644 --- a/ethereum/ethereum.go +++ b/ethereum/ethereum.go @@ -131,15 +131,14 @@ func main() { // Create a new block which we're going to mine block := ethereum.BlockChain().NewBlock(addr, txs) log.Println("Mining on new block. Includes", len(block.Transactions()), "transactions") - // Apply all transactions to the block - ethereum.StateManager().ApplyTransactions(block, block.Transactions()) ethereum.StateManager().Prepare(block.State(), block.State()) + // Apply all transactions to the block + ethereum.StateManager().ApplyTransactions(block, block.Transactions()) ethereum.StateManager().AccumelateRewards(block) // Search the nonce block.Nonce = pow.Search(block) - ethereum.Broadcast(ethwire.MsgBlockTy, []interface{}{block.Value().Val}) ethereum.StateManager().PrepareDefault(block) err := ethereum.StateManager().ProcessBlock(block) @@ -148,6 +147,7 @@ func main() { } else { log.Println("\n+++++++ MINED BLK +++++++\n", ethereum.BlockChain().CurrentBlock) log.Printf("🔨 Mined block %x\n", block.Hash()) + ethereum.Broadcast(ethwire.MsgBlockTy, []interface{}{block.Value().Val}) } } }() -- cgit v1.2.3 From cc5501b12f1b4f2297344d85f4d7f8c95b36fc34 Mon Sep 17 00:00:00 2001 From: Maran Date: Wed, 9 Apr 2014 10:29:52 -0400 Subject: Importing mnemonic support --- ethereum/ethereum.go | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) (limited to 'ethereum') diff --git a/ethereum/ethereum.go b/ethereum/ethereum.go index c82e7dcd8..e1e803771 100644 --- a/ethereum/ethereum.go +++ b/ethereum/ethereum.go @@ -11,6 +11,7 @@ import ( "os" "os/signal" "runtime" + "strings" ) const Debug = true @@ -78,7 +79,17 @@ func main() { } if r == "y" { - utils.ImportPrivateKey(ImportKey) + mnemonic := strings.Split(ImportKey, " ") + if len(mnemonic) == 24 { + fmt.Println("Got mnemonic key, importing.") + key := ethutil.MnemonicDecode(mnemonic) + utils.ImportPrivateKey(key) + } else if len(mnemonic) == 1 { + fmt.Println("Got hex key, importing.") + utils.ImportPrivateKey(ImportKey) + } else { + fmt.Println("Did not recognise format, exiting.") + } os.Exit(0) } } else { -- cgit v1.2.3 From 1cd7d4456b80c38f343cb54a624408c28c5acb13 Mon Sep 17 00:00:00 2001 From: obscuren Date: Wed, 16 Apr 2014 04:08:25 +0200 Subject: Updated to use new state object --- ethereum/dev_console.go | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) (limited to 'ethereum') diff --git a/ethereum/dev_console.go b/ethereum/dev_console.go index 421c3fa60..0f03b5e53 100644 --- a/ethereum/dev_console.go +++ b/ethereum/dev_console.go @@ -11,8 +11,7 @@ import ( "github.com/ethereum/eth-go/ethdb" "github.com/ethereum/eth-go/ethutil" "github.com/ethereum/eth-go/ethwire" - "github.com/obscuren/mutan" - _ "math/big" + "github.com/ethereum/go-ethereum/utils" "os" "strings" ) @@ -171,7 +170,7 @@ func (i *Console) ParseInput(input string) bool { if err != nil { fmt.Println("recipient err:", err) } else { - tx := ethchain.NewTransactionMessage(recipient, ethutil.Big(tokens[2]), ethutil.Big(tokens[3]), ethutil.Big(tokens[4]), []string{""}) + tx := ethchain.NewTransactionMessage(recipient, ethutil.Big(tokens[2]), ethutil.Big(tokens[3]), ethutil.Big(tokens[4]), nil) key := ethutil.Config.Db.GetKeys()[0] tx.Sign(key.PrivateKey) @@ -190,15 +189,22 @@ func (i *Console) ParseInput(input string) bool { } case "contract": fmt.Println("Contract editor (Ctrl-D = done)") - asm, err := mutan.Compile(strings.NewReader(i.Editor()), false) + + mainInput, initInput := ethutil.PreProcess(i.Editor()) + mainScript, err := utils.Compile(mainInput) if err != nil { fmt.Println(err) + break } + initScript, err := utils.Compile(initInput) + if err != nil { + fmt.Println(err) - code := ethutil.Assemble(asm) + break + } - contract := ethchain.NewContractCreationTx(ethutil.Big(tokens[0]), ethutil.Big(tokens[1]), code) + contract := ethchain.NewContractCreationTx(ethutil.Big(tokens[0]), ethutil.Big(tokens[1]), mainScript, initScript) key := ethutil.Config.Db.GetKeys()[0] contract.Sign(key.PrivateKey) -- cgit v1.2.3 From 7f0c974008b62115c5c2685dee909b379ca1c6fc Mon Sep 17 00:00:00 2001 From: zelig Date: Wed, 16 Apr 2014 13:36:52 +0100 Subject: empty string -> empty byte array --- ethereum/dev_console.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'ethereum') diff --git a/ethereum/dev_console.go b/ethereum/dev_console.go index 421c3fa60..577b039ad 100644 --- a/ethereum/dev_console.go +++ b/ethereum/dev_console.go @@ -171,7 +171,7 @@ func (i *Console) ParseInput(input string) bool { if err != nil { fmt.Println("recipient err:", err) } else { - tx := ethchain.NewTransactionMessage(recipient, ethutil.Big(tokens[2]), ethutil.Big(tokens[3]), ethutil.Big(tokens[4]), []string{""}) + tx := ethchain.NewTransactionMessage(recipient, ethutil.Big(tokens[2]), ethutil.Big(tokens[3]), ethutil.Big(tokens[4]), []byte{}) key := ethutil.Config.Db.GetKeys()[0] tx.Sign(key.PrivateKey) -- cgit v1.2.3 From f4c13f865634bae6c9cc7cd0478b7765a24fa695 Mon Sep 17 00:00:00 2001 From: zelig Date: Wed, 16 Apr 2014 13:37:04 +0100 Subject: logfile - add logfile option to ethereum client flags - fallback to StdOut - Logger appended to ethutil.Config.Log loggers - wrapper uses ethutil.Config.Log --- ethereum/config.go | 4 ++-- ethereum/ethereum.go | 26 +++++++++++++++++++++----- 2 files changed, 23 insertions(+), 7 deletions(-) (limited to 'ethereum') diff --git a/ethereum/config.go b/ethereum/config.go index e4935dfed..899a17ca6 100644 --- a/ethereum/config.go +++ b/ethereum/config.go @@ -15,8 +15,7 @@ var GenAddr bool var UseSeed bool var ImportKey string var ExportKey bool - -//var UseGui bool +var LogFile string var DataDir string func Init() { @@ -29,6 +28,7 @@ func Init() { flag.BoolVar(&GenAddr, "genaddr", false, "create a new priv/pub key") flag.BoolVar(&ExportKey, "export", false, "export private key") flag.StringVar(&OutboundPort, "p", "30303", "listening port") + flag.StringVar(&LogFile, "logfile", "", "log file (defaults to standard output)") flag.StringVar(&DataDir, "dir", ".ethereum", "ethereum data directory") flag.StringVar(&ImportKey, "import", "", "imports the given private key (hex)") flag.IntVar(&MaxPeer, "x", 5, "maximum desired peers") diff --git a/ethereum/ethereum.go b/ethereum/ethereum.go index e1e803771..f00c75ad0 100644 --- a/ethereum/ethereum.go +++ b/ethereum/ethereum.go @@ -25,7 +25,6 @@ func RegisterInterupts(s *eth.Ethereum) { go func() { for sig := range c { fmt.Printf("Shutting down (%v) ... \n", sig) - s.Stop() } }() @@ -36,8 +35,25 @@ func main() { runtime.GOMAXPROCS(runtime.NumCPU()) - ethchain.InitFees() + // set logger + var logger *log.Logger + flags := log.LstdFlags + + if LogFile != "" { + logfile, err := os.OpenFile(LogFile, os.O_RDWR | os.O_CREATE | os.O_APPEND, 0666) + if err != nil { + panic(fmt.Sprintf("error opening log file '%s': %v", LogFile, err)) + } + defer logfile.Close() + log.SetOutput(logfile) + logger = log.New(logfile, "", flags) + } else { + logger = log.New(os.Stdout, "", flags) + } ethutil.ReadConfig(DataDir) + ethutil.Config.Log.AddLogSystem(logger) + + ethchain.InitFees() ethutil.Config.Seed = UseSeed // Instantiated a eth stack @@ -108,7 +124,7 @@ func main() { os.Exit(0) } - log.Printf("Starting Ethereum v%s\n", ethutil.Config.Ver) + ethutil.Config.Log.Infoln(fmt.Sprintf("Starting Ethereum v%s", ethutil.Config.Ver)) // Set the max peers ethereum.MaxPeers = MaxPeer @@ -128,13 +144,13 @@ func main() { ethereum.Start() if StartMining { - log.Printf("Miner started\n") + ethutil.Config.Log.Infoln("Miner started") // Fake block mining. It broadcasts a new block every 5 seconds go func() { if StartMining { - log.Printf("Miner started\n") + ethutil.Config.Log.Infoln("Miner started") go func() { data, _ := ethutil.Config.Db.Get([]byte("KeyRing")) -- cgit v1.2.3 From 32b09d652de90d1626888c4ed6b61fb5bce0a7dc Mon Sep 17 00:00:00 2001 From: zelig Date: Wed, 16 Apr 2014 14:57:51 +0100 Subject: non-interactive option - add -y flag for non-interactive use - refactor main - output to logfile (not ideal..) but not to all ethutil loggers for privacy --- ethereum/config.go | 2 + ethereum/ethereum.go | 104 +++++++++++++++++++++++---------------------------- 2 files changed, 49 insertions(+), 57 deletions(-) (limited to 'ethereum') diff --git a/ethereum/config.go b/ethereum/config.go index 899a17ca6..b796af5cd 100644 --- a/ethereum/config.go +++ b/ethereum/config.go @@ -17,12 +17,14 @@ var ImportKey string var ExportKey bool var LogFile string var DataDir string +var NonInteractive bool func Init() { flag.BoolVar(&StartConsole, "c", false, "debug and testing console") flag.BoolVar(&StartMining, "m", false, "start dagger mining") flag.BoolVar(&ShowGenesis, "g", false, "prints genesis header and exits") //flag.BoolVar(&UseGui, "gui", true, "use the gui") + flag.BoolVar(&NonInteractive, "y", false, "non-interactive mode (say yes to confirmations)") flag.BoolVar(&UseUPnP, "upnp", false, "enable UPnP support") flag.BoolVar(&UseSeed, "seed", true, "seed peers") flag.BoolVar(&GenAddr, "genaddr", false, "create a new priv/pub key") diff --git a/ethereum/ethereum.go b/ethereum/ethereum.go index f00c75ad0..4f5c3756a 100644 --- a/ethereum/ethereum.go +++ b/ethereum/ethereum.go @@ -30,13 +30,27 @@ func RegisterInterupts(s *eth.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" +} + func main() { Init() runtime.GOMAXPROCS(runtime.NumCPU()) // set logger - var logger *log.Logger + var logSys *log.Logger flags := log.LstdFlags if LogFile != "" { @@ -46,12 +60,13 @@ func main() { } defer logfile.Close() log.SetOutput(logfile) - logger = log.New(logfile, "", flags) + logSys = log.New(logfile, "", flags) } else { - logger = log.New(os.Stdout, "", flags) + logSys = log.New(os.Stdout, "", flags) } ethutil.ReadConfig(DataDir) - ethutil.Config.Log.AddLogSystem(logger) + logger := ethutil.Config.Log + logger.AddLogSystem(logSys) ethchain.InitFees() ethutil.Config.Seed = UseSeed @@ -64,67 +79,42 @@ func main() { } ethereum.Port = OutboundPort - if GenAddr { - fmt.Println("This action overwrites your old private key. 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) - } - } - - if r == "y" { + // bookkeeping tasks + switch { + case GenAddr: + if NonInteractive || confirm("This action overwrites your old private key.") { utils.CreateKeyPair(true) } os.Exit(0) - } else { - if len(ImportKey) > 0 { - fmt.Println("This action overwrites your old private key. 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) - } - } - - if r == "y" { - mnemonic := strings.Split(ImportKey, " ") - if len(mnemonic) == 24 { - fmt.Println("Got mnemonic key, importing.") - key := ethutil.MnemonicDecode(mnemonic) - utils.ImportPrivateKey(key) - } else if len(mnemonic) == 1 { - fmt.Println("Got hex key, importing.") - utils.ImportPrivateKey(ImportKey) - } else { - fmt.Println("Did not recognise format, exiting.") - } - os.Exit(0) + case len(ImportKey) > 0: + if NonInteractive || confirm("This action overwrites your old private key.") { + mnemonic := strings.Split(ImportKey, " ") + if len(mnemonic) == 24 { + logSys.Println("Got mnemonic key, importing.") + key := ethutil.MnemonicDecode(mnemonic) + utils.ImportPrivateKey(key) + } else if len(mnemonic) == 1 { + logSys.Println("Got hex key, importing.") + utils.ImportPrivateKey(ImportKey) + } else { + logSys.Println("Did not recognise format, exiting.") } - } else { - utils.CreateKeyPair(false) } - } - - if ExportKey { + os.Exit(0) + case len(ImportKey) == 0: + utils.CreateKeyPair(false) + fallthrough + case ExportKey: key := ethutil.Config.Db.GetKeys()[0] - fmt.Printf("%x\n", key.PrivateKey) + logSys.Println(fmt.Sprintf("prvk: %x\n", key.PrivateKey)) os.Exit(0) - } - - if ShowGenesis { - fmt.Println(ethereum.BlockChain().Genesis()) + case ShowGenesis: + logSys.Println(ethereum.BlockChain().Genesis()) os.Exit(0) } - ethutil.Config.Log.Infoln(fmt.Sprintf("Starting Ethereum v%s", ethutil.Config.Ver)) + // client + logger.Infoln(fmt.Sprintf("Starting Ethereum v%s", ethutil.Config.Ver)) // Set the max peers ethereum.MaxPeers = MaxPeer @@ -144,13 +134,13 @@ func main() { ethereum.Start() if StartMining { - ethutil.Config.Log.Infoln("Miner started") + logger.Infoln("Miner started") // Fake block mining. It broadcasts a new block every 5 seconds go func() { if StartMining { - ethutil.Config.Log.Infoln("Miner started") + logger.Infoln("Miner started") go func() { data, _ := ethutil.Config.Db.Get([]byte("KeyRing")) -- cgit v1.2.3 From 59a7b130191286f141a40d294981805677414eb5 Mon Sep 17 00:00:00 2001 From: zelig Date: Wed, 16 Apr 2014 15:01:22 +0100 Subject: typo interrupt --- ethereum/ethereum.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'ethereum') diff --git a/ethereum/ethereum.go b/ethereum/ethereum.go index 4f5c3756a..881f39ece 100644 --- a/ethereum/ethereum.go +++ b/ethereum/ethereum.go @@ -17,7 +17,7 @@ import ( const Debug = true // Register interrupt handlers so we can stop the ethereum -func RegisterInterupts(s *eth.Ethereum) { +func RegisterInterrupts(s *eth.Ethereum) { // Buffered chan of one is enough c := make(chan os.Signal, 1) // Notify about interrupts for now @@ -130,7 +130,7 @@ func main() { go console.Start() } - RegisterInterupts(ethereum) + RegisterInterrupts(ethereum) ethereum.Start() if StartMining { -- cgit v1.2.3 From b962779a1318138e08c6e84a537fdbc6c9ebfd97 Mon Sep 17 00:00:00 2001 From: obscuren Date: Wed, 23 Apr 2014 11:51:48 +0200 Subject: Minor update and fixes to the gui and console --- ethereum/dev_console.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'ethereum') diff --git a/ethereum/dev_console.go b/ethereum/dev_console.go index 0f03b5e53..583b8bd0b 100644 --- a/ethereum/dev_console.go +++ b/ethereum/dev_console.go @@ -204,7 +204,7 @@ func (i *Console) ParseInput(input string) bool { break } - contract := ethchain.NewContractCreationTx(ethutil.Big(tokens[0]), ethutil.Big(tokens[1]), mainScript, initScript) + contract := ethchain.NewContractCreationTx(ethutil.Big(tokens[0]), ethutil.Big(tokens[1]), ethutil.Big(tokens[1]), mainScript, initScript) key := ethutil.Config.Db.GetKeys()[0] contract.Sign(key.PrivateKey) -- cgit v1.2.3 From e16fd323e800297602a60b7a0e7b7897a55d2fa0 Mon Sep 17 00:00:00 2001 From: obscuren Date: Sat, 26 Apr 2014 01:47:04 +0200 Subject: Leverage the new watch & address:changed functionality --- ethereum/ethereum.go | 32 +++++++++++++++++--------------- 1 file changed, 17 insertions(+), 15 deletions(-) (limited to 'ethereum') diff --git a/ethereum/ethereum.go b/ethereum/ethereum.go index 881f39ece..04851d2bd 100644 --- a/ethereum/ethereum.go +++ b/ethereum/ethereum.go @@ -53,22 +53,24 @@ func main() { var logSys *log.Logger flags := log.LstdFlags + ethutil.ReadConfig(DataDir) + logger := ethutil.Config.Log + if LogFile != "" { - logfile, err := os.OpenFile(LogFile, os.O_RDWR | os.O_CREATE | os.O_APPEND, 0666) - if err != nil { - panic(fmt.Sprintf("error opening log file '%s': %v", LogFile, err)) - } - defer logfile.Close() + logfile, err := os.OpenFile(LogFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) + if err != nil { + panic(fmt.Sprintf("error opening log file '%s': %v", LogFile, err)) + } + defer logfile.Close() log.SetOutput(logfile) logSys = log.New(logfile, "", flags) - } else { - logSys = log.New(os.Stdout, "", flags) - } - ethutil.ReadConfig(DataDir) - logger := ethutil.Config.Log - logger.AddLogSystem(logSys) + logger.AddLogSystem(logSys) + } + /*else { + logSys = log.New(os.Stdout, "", flags) + }*/ - ethchain.InitFees() + ethchain.InitFees() ethutil.Config.Seed = UseSeed // Instantiated a eth stack @@ -101,9 +103,6 @@ func main() { } } os.Exit(0) - case len(ImportKey) == 0: - utils.CreateKeyPair(false) - fallthrough case ExportKey: key := ethutil.Config.Db.GetKeys()[0] logSys.Println(fmt.Sprintf("prvk: %x\n", key.PrivateKey)) @@ -111,6 +110,9 @@ func main() { case ShowGenesis: logSys.Println(ethereum.BlockChain().Genesis()) os.Exit(0) + default: + // Creates a keypair if non exists + utils.CreateKeyPair(false) } // client -- cgit v1.2.3 From 922974c760278b6d49cb6f286b663d60f77d5248 Mon Sep 17 00:00:00 2001 From: obscuren Date: Mon, 28 Apr 2014 23:24:42 +0200 Subject: Added muted --- ethereum/dev_console.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'ethereum') diff --git a/ethereum/dev_console.go b/ethereum/dev_console.go index 583b8bd0b..d2be43205 100644 --- a/ethereum/dev_console.go +++ b/ethereum/dev_console.go @@ -12,6 +12,7 @@ import ( "github.com/ethereum/eth-go/ethutil" "github.com/ethereum/eth-go/ethwire" "github.com/ethereum/go-ethereum/utils" + "github.com/obscuren/mutan" "os" "strings" ) @@ -190,7 +191,7 @@ func (i *Console) ParseInput(input string) bool { case "contract": fmt.Println("Contract editor (Ctrl-D = done)") - mainInput, initInput := ethutil.PreProcess(i.Editor()) + mainInput, initInput := mutan.PreProcess(i.Editor()) mainScript, err := utils.Compile(mainInput) if err != nil { fmt.Println(err) -- cgit v1.2.3 From 3424bf17ca791b97ea512bef5290d1a52c1758af Mon Sep 17 00:00:00 2001 From: Maran Date: Fri, 2 May 2014 13:35:03 +0200 Subject: Moved RPC Server and implemented it as a package --- ethereum/config.go | 2 ++ ethereum/ethereum.go | 5 +++++ 2 files changed, 7 insertions(+) (limited to 'ethereum') diff --git a/ethereum/config.go b/ethereum/config.go index b796af5cd..234e79f12 100644 --- a/ethereum/config.go +++ b/ethereum/config.go @@ -6,6 +6,7 @@ import ( var StartConsole bool var StartMining bool +var StartRpc bool var UseUPnP bool var OutboundPort string var ShowGenesis bool @@ -24,6 +25,7 @@ func Init() { flag.BoolVar(&StartMining, "m", false, "start dagger mining") flag.BoolVar(&ShowGenesis, "g", false, "prints genesis header and exits") //flag.BoolVar(&UseGui, "gui", true, "use the gui") + flag.BoolVar(&StartRpc, "r", false, "start rpc server") flag.BoolVar(&NonInteractive, "y", false, "non-interactive mode (say yes to confirmations)") flag.BoolVar(&UseUPnP, "upnp", false, "enable UPnP support") flag.BoolVar(&UseSeed, "seed", true, "seed peers") diff --git a/ethereum/ethereum.go b/ethereum/ethereum.go index 04851d2bd..0b56855e0 100644 --- a/ethereum/ethereum.go +++ b/ethereum/ethereum.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/ethereum/eth-go" "github.com/ethereum/eth-go/ethchain" + "github.com/ethereum/eth-go/etherpc" "github.com/ethereum/eth-go/ethminer" "github.com/ethereum/eth-go/ethutil" "github.com/ethereum/go-ethereum/utils" @@ -131,6 +132,10 @@ func main() { console := NewConsole(ethereum) go console.Start() } + if StartRpc { + ethereum.RpcServer = etherpc.NewJsonRpcServer() + go ethereum.RpcServer.Start() + } RegisterInterrupts(ethereum) ethereum.Start() -- cgit v1.2.3 From bcb3ad733258b3d8f639763c2c78c85f43b2c826 Mon Sep 17 00:00:00 2001 From: Maran Date: Fri, 2 May 2014 20:01:25 +0200 Subject: Fix circular deps --- ethereum/ethereum.go | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'ethereum') diff --git a/ethereum/ethereum.go b/ethereum/ethereum.go index 0b56855e0..829f71e39 100644 --- a/ethereum/ethereum.go +++ b/ethereum/ethereum.go @@ -6,6 +6,7 @@ import ( "github.com/ethereum/eth-go/ethchain" "github.com/ethereum/eth-go/etherpc" "github.com/ethereum/eth-go/ethminer" + "github.com/ethereum/eth-go/ethpub" "github.com/ethereum/eth-go/ethutil" "github.com/ethereum/go-ethereum/utils" "log" @@ -133,8 +134,10 @@ func main() { go console.Start() } if StartRpc { - ethereum.RpcServer = etherpc.NewJsonRpcServer() - go ethereum.RpcServer.Start() + // TODO: Can we make this work again? + //ethereum.RpcServer = etherpc.NewJsonRpcServer(ethpub.NewPEthereum(ethereum)) + rpc := etherpc.NewJsonRpcServer(ethpub.NewPEthereum(ethereum)) + go rpc.Start() } RegisterInterrupts(ethereum) -- cgit v1.2.3 From e94e5ac75dbbc4ec52228ae11377a4fa71ab95ab Mon Sep 17 00:00:00 2001 From: Maran Date: Mon, 5 May 2014 14:16:14 +0200 Subject: Implemented rpc for ethereal and ethereum --- ethereum/ethereum.go | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) (limited to 'ethereum') diff --git a/ethereum/ethereum.go b/ethereum/ethereum.go index 829f71e39..1315c0120 100644 --- a/ethereum/ethereum.go +++ b/ethereum/ethereum.go @@ -134,10 +134,8 @@ func main() { go console.Start() } if StartRpc { - // TODO: Can we make this work again? - //ethereum.RpcServer = etherpc.NewJsonRpcServer(ethpub.NewPEthereum(ethereum)) - rpc := etherpc.NewJsonRpcServer(ethpub.NewPEthereum(ethereum)) - go rpc.Start() + ethereum.RpcServer = etherpc.NewJsonRpcServer(ethpub.NewPEthereum(ethereum.StateManager(), ethereum.BlockChain(), ethereum.TxPool())) + go ethereum.RpcServer.Start() } RegisterInterrupts(ethereum) -- cgit v1.2.3 From c9852c4929c39ab47eab7b70f9304432f2c8225e Mon Sep 17 00:00:00 2001 From: Maran Date: Mon, 5 May 2014 15:15:04 +0200 Subject: Renamed etherpc to ethrpc All work and no play makes Maran a dull boy --- ethereum/ethereum.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'ethereum') diff --git a/ethereum/ethereum.go b/ethereum/ethereum.go index 1315c0120..8719f3e87 100644 --- a/ethereum/ethereum.go +++ b/ethereum/ethereum.go @@ -4,9 +4,9 @@ import ( "fmt" "github.com/ethereum/eth-go" "github.com/ethereum/eth-go/ethchain" - "github.com/ethereum/eth-go/etherpc" "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/go-ethereum/utils" "log" @@ -134,7 +134,7 @@ func main() { go console.Start() } if StartRpc { - ethereum.RpcServer = etherpc.NewJsonRpcServer(ethpub.NewPEthereum(ethereum.StateManager(), ethereum.BlockChain(), ethereum.TxPool())) + ethereum.RpcServer = ethrpc.NewJsonRpcServer(ethpub.NewPEthereum(ethereum.StateManager(), ethereum.BlockChain(), ethereum.TxPool())) go ethereum.RpcServer.Start() } -- cgit v1.2.3 From 0bf2d24cb030ec53abedf483189ecbaa3c9676be Mon Sep 17 00:00:00 2001 From: obscuren Date: Fri, 9 May 2014 14:51:02 +0200 Subject: Changed seeding --- ethereum/ethereum.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'ethereum') diff --git a/ethereum/ethereum.go b/ethereum/ethereum.go index 8719f3e87..2f05bf2a1 100644 --- a/ethereum/ethereum.go +++ b/ethereum/ethereum.go @@ -73,7 +73,6 @@ func main() { }*/ ethchain.InitFees() - ethutil.Config.Seed = UseSeed // Instantiated a eth stack ethereum, err := eth.New(eth.CapDefault, UseUPnP) @@ -139,7 +138,8 @@ func main() { } RegisterInterrupts(ethereum) - ethereum.Start() + + ethereum.Start(UseSeed) if StartMining { logger.Infoln("Miner started") -- cgit v1.2.3 From 5d15563ea768e03a6aef28e0b7cff4fa871cca08 Mon Sep 17 00:00:00 2001 From: obscuren Date: Mon, 12 May 2014 12:22:16 +0200 Subject: PreProcess => PreParse --- ethereum/dev_console.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'ethereum') diff --git a/ethereum/dev_console.go b/ethereum/dev_console.go index d2be43205..9bdd58942 100644 --- a/ethereum/dev_console.go +++ b/ethereum/dev_console.go @@ -191,7 +191,7 @@ func (i *Console) ParseInput(input string) bool { case "contract": fmt.Println("Contract editor (Ctrl-D = done)") - mainInput, initInput := mutan.PreProcess(i.Editor()) + mainInput, initInput := mutan.PreParse(i.Editor()) mainScript, err := utils.Compile(mainInput) if err != nil { fmt.Println(err) -- cgit v1.2.3 From cf7ab072644c9427501f9a29d7ad5c5492edf062 Mon Sep 17 00:00:00 2001 From: Maran Date: Mon, 12 May 2014 13:41:52 +0200 Subject: Disable seed by default Seed host seems down, only causes timeouts, not helpful --- ethereum/config.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'ethereum') diff --git a/ethereum/config.go b/ethereum/config.go index 234e79f12..db1391881 100644 --- a/ethereum/config.go +++ b/ethereum/config.go @@ -28,7 +28,7 @@ func Init() { flag.BoolVar(&StartRpc, "r", false, "start rpc server") flag.BoolVar(&NonInteractive, "y", false, "non-interactive mode (say yes to confirmations)") flag.BoolVar(&UseUPnP, "upnp", false, "enable UPnP support") - flag.BoolVar(&UseSeed, "seed", true, "seed peers") + flag.BoolVar(&UseSeed, "seed", false, "seed peers") flag.BoolVar(&GenAddr, "genaddr", false, "create a new priv/pub key") flag.BoolVar(&ExportKey, "export", false, "export private key") flag.StringVar(&OutboundPort, "p", "30303", "listening port") -- cgit v1.2.3 From a5963d1377ab1a4a82d5b2881e820121ac3da564 Mon Sep 17 00:00:00 2001 From: Maran Date: Tue, 13 May 2014 11:34:47 +0200 Subject: Enable seed again --- ethereum/config.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'ethereum') diff --git a/ethereum/config.go b/ethereum/config.go index db1391881..234e79f12 100644 --- a/ethereum/config.go +++ b/ethereum/config.go @@ -28,7 +28,7 @@ func Init() { flag.BoolVar(&StartRpc, "r", false, "start rpc server") flag.BoolVar(&NonInteractive, "y", false, "non-interactive mode (say yes to confirmations)") flag.BoolVar(&UseUPnP, "upnp", false, "enable UPnP support") - flag.BoolVar(&UseSeed, "seed", false, "seed peers") + flag.BoolVar(&UseSeed, "seed", true, "seed peers") flag.BoolVar(&GenAddr, "genaddr", false, "create a new priv/pub key") flag.BoolVar(&ExportKey, "export", false, "export private key") flag.StringVar(&OutboundPort, "p", "30303", "listening port") -- cgit v1.2.3 From b9876df5dc719f583172017cc71af146c6f732a9 Mon Sep 17 00:00:00 2001 From: Maran Date: Tue, 13 May 2014 11:48:52 +0200 Subject: Added support to NewJsonRpc to return an error as well as an interface --- ethereum/ethereum.go | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) (limited to 'ethereum') diff --git a/ethereum/ethereum.go b/ethereum/ethereum.go index 2f05bf2a1..8ef061be0 100644 --- a/ethereum/ethereum.go +++ b/ethereum/ethereum.go @@ -133,8 +133,12 @@ func main() { go console.Start() } if StartRpc { - ethereum.RpcServer = ethrpc.NewJsonRpcServer(ethpub.NewPEthereum(ethereum.StateManager(), ethereum.BlockChain(), ethereum.TxPool())) - go ethereum.RpcServer.Start() + ethereum.RpcServer, err = ethrpc.NewJsonRpcServer(ethpub.NewPEthereum(ethereum.StateManager(), ethereum.BlockChain(), ethereum.TxPool())) + if err != nil { + logger.Infoln("Could not start RPC interface:", err) + } else { + go ethereum.RpcServer.Start() + } } RegisterInterrupts(ethereum) -- cgit v1.2.3 From 9a03df7bd831f1b66bc02510a4abed878f4ffa17 Mon Sep 17 00:00:00 2001 From: Maran Date: Tue, 13 May 2014 12:00:48 +0200 Subject: Implemented a flag for a different RPC port; --rpcport --- ethereum/config.go | 2 ++ ethereum/ethereum.go | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) (limited to 'ethereum') diff --git a/ethereum/config.go b/ethereum/config.go index 234e79f12..7ca1a9801 100644 --- a/ethereum/config.go +++ b/ethereum/config.go @@ -7,6 +7,7 @@ import ( var StartConsole bool var StartMining bool var StartRpc bool +var RpcPort int var UseUPnP bool var OutboundPort string var ShowGenesis bool @@ -26,6 +27,7 @@ func Init() { flag.BoolVar(&ShowGenesis, "g", false, "prints genesis header and exits") //flag.BoolVar(&UseGui, "gui", true, "use the gui") flag.BoolVar(&StartRpc, "r", false, "start rpc server") + flag.IntVar(&RpcPort, "rpcport", 8080, "port to start json-rpc server on") flag.BoolVar(&NonInteractive, "y", false, "non-interactive mode (say yes to confirmations)") flag.BoolVar(&UseUPnP, "upnp", false, "enable UPnP support") flag.BoolVar(&UseSeed, "seed", true, "seed peers") diff --git a/ethereum/ethereum.go b/ethereum/ethereum.go index 8ef061be0..d49b5dc8a 100644 --- a/ethereum/ethereum.go +++ b/ethereum/ethereum.go @@ -133,7 +133,7 @@ func main() { go console.Start() } if StartRpc { - ethereum.RpcServer, err = ethrpc.NewJsonRpcServer(ethpub.NewPEthereum(ethereum.StateManager(), ethereum.BlockChain(), ethereum.TxPool())) + ethereum.RpcServer, err = ethrpc.NewJsonRpcServer(ethpub.NewPEthereum(ethereum.StateManager(), ethereum.BlockChain(), ethereum.TxPool()), RpcPort) if err != nil { logger.Infoln("Could not start RPC interface:", err) } else { -- cgit v1.2.3 From 32c6126593100d37c38e423ec62c56938e5f9155 Mon Sep 17 00:00:00 2001 From: obscuren Date: Tue, 13 May 2014 12:45:47 +0200 Subject: Fix --- ethereum/ethereum.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'ethereum') diff --git a/ethereum/ethereum.go b/ethereum/ethereum.go index 8ef061be0..b60eb4181 100644 --- a/ethereum/ethereum.go +++ b/ethereum/ethereum.go @@ -133,7 +133,7 @@ func main() { go console.Start() } if StartRpc { - ethereum.RpcServer, err = ethrpc.NewJsonRpcServer(ethpub.NewPEthereum(ethereum.StateManager(), ethereum.BlockChain(), ethereum.TxPool())) + ethereum.RpcServer, err = ethrpc.NewJsonRpcServer(ethpub.NewPEthereum(ethereum)) if err != nil { logger.Infoln("Could not start RPC interface:", err) } else { -- cgit v1.2.3 From 20ea78945e751a1ad11e2b2fc7c4224f4c46e108 Mon Sep 17 00:00:00 2001 From: Maran Date: Tue, 13 May 2014 14:43:08 +0200 Subject: Implemented new JS/EthPub methods - getTxCountAt - getPeerCount - getIsMining - getIsListening - getCoinbase --- ethereum/ethereum.go | 47 +++++++++++++++++++++++++---------------------- 1 file changed, 25 insertions(+), 22 deletions(-) (limited to 'ethereum') diff --git a/ethereum/ethereum.go b/ethereum/ethereum.go index 5b578deba..8b22533d9 100644 --- a/ethereum/ethereum.go +++ b/ethereum/ethereum.go @@ -122,28 +122,8 @@ func main() { // Set the max peers ethereum.MaxPeers = MaxPeer - if StartConsole { - err := os.Mkdir(ethutil.Config.ExecPath, os.ModePerm) - // Error is OK if the error is ErrExist - if err != nil && !os.IsExist(err) { - log.Panic("Unable to create EXECPATH:", err) - } - - console := NewConsole(ethereum) - go console.Start() - } - if StartRpc { - ethereum.RpcServer, err = ethrpc.NewJsonRpcServer(ethpub.NewPEthereum(ethereum), RpcPort) - if err != nil { - logger.Infoln("Could not start RPC interface:", err) - } else { - go ethereum.RpcServer.Start() - } - } - - RegisterInterrupts(ethereum) - - ethereum.Start(UseSeed) + // Set Mining status + ethereum.Mining = StartMining if StartMining { logger.Infoln("Miner started") @@ -168,6 +148,29 @@ func main() { } + if StartConsole { + err := os.Mkdir(ethutil.Config.ExecPath, os.ModePerm) + // Error is OK if the error is ErrExist + if err != nil && !os.IsExist(err) { + log.Panic("Unable to create EXECPATH:", err) + } + + console := NewConsole(ethereum) + go console.Start() + } + if StartRpc { + ethereum.RpcServer, err = ethrpc.NewJsonRpcServer(ethpub.NewPEthereum(ethereum), RpcPort) + if err != nil { + logger.Infoln("Could not start RPC interface:", err) + } else { + go ethereum.RpcServer.Start() + } + } + + RegisterInterrupts(ethereum) + + ethereum.Start(UseSeed) + // Wait for shutdown ethereum.WaitForShutdown() } -- cgit v1.2.3 From 54eff2d778ef6e8a84d336d4fb14a5a35728340c Mon Sep 17 00:00:00 2001 From: Maran Date: Tue, 13 May 2014 14:48:45 +0200 Subject: Change coinbase to be the address not public key --- ethereum/ethereum.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'ethereum') diff --git a/ethereum/ethereum.go b/ethereum/ethereum.go index 8b22533d9..babebbb48 100644 --- a/ethereum/ethereum.go +++ b/ethereum/ethereum.go @@ -1,6 +1,7 @@ package main import ( + "encoding/hex" "fmt" "github.com/ethereum/eth-go" "github.com/ethereum/eth-go/ethchain" @@ -139,7 +140,9 @@ func main() { keyRing := ethutil.NewValueFromBytes(data) addr := keyRing.Get(1).Bytes() - miner := ethminer.NewDefaultMiner(addr, ethereum) + pair, _ := ethchain.NewKeyPairFromSec(ethutil.FromHex(hex.EncodeToString(addr))) + + miner := ethminer.NewDefaultMiner(pair.Address(), ethereum) miner.Start() }() -- cgit v1.2.3 From 0d9c948b9b2c5eef6f0069f9aa05e9868f939444 Mon Sep 17 00:00:00 2001 From: Maran Date: Wed, 14 May 2014 12:24:49 +0200 Subject: Generate coinbase from privatekey, not pubkey. Partily fixes #43 --- ethereum/ethereum.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'ethereum') diff --git a/ethereum/ethereum.go b/ethereum/ethereum.go index babebbb48..055cc0bc4 100644 --- a/ethereum/ethereum.go +++ b/ethereum/ethereum.go @@ -138,7 +138,7 @@ func main() { go func() { data, _ := ethutil.Config.Db.Get([]byte("KeyRing")) keyRing := ethutil.NewValueFromBytes(data) - addr := keyRing.Get(1).Bytes() + addr := keyRing.Get(0).Bytes() pair, _ := ethchain.NewKeyPairFromSec(ethutil.FromHex(hex.EncodeToString(addr))) -- 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 --- ethereum/ethereum.go | 25 +------------------------ 1 file changed, 1 insertion(+), 24 deletions(-) (limited to 'ethereum') diff --git a/ethereum/ethereum.go b/ethereum/ethereum.go index 055cc0bc4..207e61c88 100644 --- a/ethereum/ethereum.go +++ b/ethereum/ethereum.go @@ -1,11 +1,9 @@ package main import ( - "encoding/hex" "fmt" "github.com/ethereum/eth-go" "github.com/ethereum/eth-go/ethchain" - "github.com/ethereum/eth-go/ethminer" "github.com/ethereum/eth-go/ethpub" "github.com/ethereum/eth-go/ethrpc" "github.com/ethereum/eth-go/ethutil" @@ -127,28 +125,7 @@ func main() { ethereum.Mining = StartMining if StartMining { - logger.Infoln("Miner started") - - // Fake block mining. It broadcasts a new block every 5 seconds - go func() { - - if StartMining { - logger.Infoln("Miner started") - - 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() - - }() - } - }() - + utils.DoMining(ethereum) } if StartConsole { -- 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 --- ethereum/ethereum.go | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) (limited to 'ethereum') diff --git a/ethereum/ethereum.go b/ethereum/ethereum.go index 207e61c88..448223c37 100644 --- a/ethereum/ethereum.go +++ b/ethereum/ethereum.go @@ -4,8 +4,6 @@ import ( "fmt" "github.com/ethereum/eth-go" "github.com/ethereum/eth-go/ethchain" - "github.com/ethereum/eth-go/ethpub" - "github.com/ethereum/eth-go/ethrpc" "github.com/ethereum/eth-go/ethutil" "github.com/ethereum/go-ethereum/utils" "log" @@ -139,12 +137,7 @@ func main() { go console.Start() } if StartRpc { - ethereum.RpcServer, err = ethrpc.NewJsonRpcServer(ethpub.NewPEthereum(ethereum), RpcPort) - if err != nil { - logger.Infoln("Could not start RPC interface:", err) - } else { - go ethereum.RpcServer.Start() - } + utils.DoRpc(ethereum, RpcPort) } RegisterInterrupts(ethereum) -- 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 --- ethereum/dev_console.go | 8 ++++---- ethereum/ethereum.go | 15 +++++++++++++-- 2 files changed, 17 insertions(+), 6 deletions(-) (limited to 'ethereum') diff --git a/ethereum/dev_console.go b/ethereum/dev_console.go index 9bdd58942..5941c03ab 100644 --- a/ethereum/dev_console.go +++ b/ethereum/dev_console.go @@ -173,8 +173,8 @@ func (i *Console) ParseInput(input string) bool { } else { tx := ethchain.NewTransactionMessage(recipient, ethutil.Big(tokens[2]), ethutil.Big(tokens[3]), ethutil.Big(tokens[4]), nil) - key := ethutil.Config.Db.GetKeys()[0] - tx.Sign(key.PrivateKey) + keyPair := ethutil.GetKeyRing().Get(0) + tx.Sign(keyPair.PrivateKey) i.ethereum.TxPool().QueueTransaction(tx) fmt.Printf("%x\n", tx.Hash()) @@ -207,8 +207,8 @@ func (i *Console) ParseInput(input string) bool { contract := ethchain.NewContractCreationTx(ethutil.Big(tokens[0]), ethutil.Big(tokens[1]), ethutil.Big(tokens[1]), mainScript, initScript) - key := ethutil.Config.Db.GetKeys()[0] - contract.Sign(key.PrivateKey) + keyPair := ethutil.GetKeyRing().Get(0) + contract.Sign(keyPair.PrivateKey) i.ethereum.TxPool().QueueTransaction(contract) diff --git a/ethereum/ethereum.go b/ethereum/ethereum.go index 207e61c88..b5460ac69 100644 --- a/ethereum/ethereum.go +++ b/ethereum/ethereum.go @@ -104,8 +104,19 @@ func main() { } os.Exit(0) case ExportKey: - key := ethutil.Config.Db.GetKeys()[0] - logSys.Println(fmt.Sprintf("prvk: %x\n", key.PrivateKey)) + 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) + os.Exit(0) case ShowGenesis: logSys.Println(ethereum.BlockChain().Genesis()) -- cgit v1.2.3 From a1dcc5cd1793dc05e2ff38e8a8024690e09aebf5 Mon Sep 17 00:00:00 2001 From: Maran Date: Wed, 14 May 2014 14:11:45 +0200 Subject: Prevent crash during import of privkeys. @obscuren please check if this was commented out for a reason --- ethereum/ethereum.go | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) (limited to 'ethereum') diff --git a/ethereum/ethereum.go b/ethereum/ethereum.go index d22513972..2abf6da42 100644 --- a/ethereum/ethereum.go +++ b/ethereum/ethereum.go @@ -64,10 +64,9 @@ func main() { log.SetOutput(logfile) logSys = log.New(logfile, "", flags) logger.AddLogSystem(logSys) - } - /*else { + } else { logSys = log.New(os.Stdout, "", flags) - }*/ + } ethchain.InitFees() -- cgit v1.2.3 From cbce882f5e35300016055cde81eeccb3ae052671 Mon Sep 17 00:00:00 2001 From: obscuren Date: Thu, 15 May 2014 20:45:19 +0200 Subject: Basic javascript console --- ethereum/config.go | 2 ++ ethereum/ethereum.go | 7 ++++ ethereum/javascript_console.go | 76 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 85 insertions(+) create mode 100644 ethereum/javascript_console.go (limited to 'ethereum') diff --git a/ethereum/config.go b/ethereum/config.go index 7ca1a9801..4d7ea6310 100644 --- a/ethereum/config.go +++ b/ethereum/config.go @@ -20,6 +20,7 @@ var ExportKey bool var LogFile string var DataDir string var NonInteractive bool +var StartExp bool func Init() { flag.BoolVar(&StartConsole, "c", false, "debug and testing console") @@ -38,6 +39,7 @@ func Init() { flag.StringVar(&DataDir, "dir", ".ethereum", "ethereum data directory") flag.StringVar(&ImportKey, "import", "", "imports the given private key (hex)") flag.IntVar(&MaxPeer, "x", 5, "maximum desired peers") + flag.BoolVar(&StartExp, "ex", false, "exp") flag.Parse() } diff --git a/ethereum/ethereum.go b/ethereum/ethereum.go index 2abf6da42..8b42c2a2c 100644 --- a/ethereum/ethereum.go +++ b/ethereum/ethereum.go @@ -146,6 +146,13 @@ save these words so you can restore your account later: %s console := NewConsole(ethereum) go console.Start() } + + if StartExp { + c := NewJSConsole(ethereum) + + go c.Start() + } + if StartRpc { utils.DoRpc(ethereum, RpcPort) } diff --git a/ethereum/javascript_console.go b/ethereum/javascript_console.go new file mode 100644 index 000000000..a6449af8f --- /dev/null +++ b/ethereum/javascript_console.go @@ -0,0 +1,76 @@ +package main + +import ( + "bufio" + "fmt" + "github.com/ethereum/eth-go" + "github.com/ethereum/eth-go/ethpub" + "github.com/robertkrimen/otto" + "os" +) + +type JSConsole struct { + vm *otto.Otto + lib *ethpub.PEthereum +} + +func NewJSConsole(ethereum *eth.Ethereum) *JSConsole { + return &JSConsole{vm: otto.New(), lib: ethpub.NewPEthereum(ethereum)} +} + +func (self *JSConsole) Start() { + self.initBindings() + + fmt.Println("Eth JS Console") + reader := bufio.NewReader(os.Stdin) + for { + fmt.Printf("eth >>> ") + str, _, err := reader.ReadLine() + if err != nil { + fmt.Println("Error reading input", err) + } else { + if string(str) == "quit" { + return + } + + self.ParseInput(string(str)) + } + } +} + +func (self *JSConsole) ParseInput(code string) { + value, err := self.vm.Run(code) + if err != nil { + fmt.Println(err) + return + } + + fmt.Println(value) +} + +type OtherStruct struct { + Test string +} + +type JSWrapper struct { + pub *ethpub.PEthereum + vm *otto.Otto +} + +func (self *JSWrapper) GetKey() otto.Value { + result, err := self.vm.ToValue(self.pub.GetKey()) + if err != nil { + fmt.Println(err) + + return otto.UndefinedValue() + } + + return result + +} + +func (self *JSConsole) initBindings() { + t := &JSWrapper{self.lib, self.vm} + + self.vm.Set("eth", t) +} -- cgit v1.2.3 From 0a03484188dc23707b343bb512ec341afc744a2e Mon Sep 17 00:00:00 2001 From: obscuren Date: Thu, 15 May 2014 22:15:14 +0200 Subject: Implemented JavaScript console --- ethereum/ethereum.go | 11 +++++--- ethereum/javascript_console.go | 60 ++++++++++++++++++++++++++++++++---------- 2 files changed, 53 insertions(+), 18 deletions(-) (limited to 'ethereum') diff --git a/ethereum/ethereum.go b/ethereum/ethereum.go index 8b42c2a2c..128e11139 100644 --- a/ethereum/ethereum.go +++ b/ethereum/ethereum.go @@ -52,7 +52,12 @@ func main() { var logSys *log.Logger flags := log.LstdFlags - ethutil.ReadConfig(DataDir) + if StartJsConsole { + ethutil.ReadConfig(DataDir, ethutil.LogFile) + } else { + ethutil.ReadConfig(DataDir, ethutil.LogFile|ethutil.LogStd) + } + logger := ethutil.Config.Log if LogFile != "" { @@ -145,9 +150,7 @@ save these words so you can restore your account later: %s console := NewConsole(ethereum) go console.Start() - } - - if StartExp { + } else if StartJsConsole { c := NewJSConsole(ethereum) go c.Start() diff --git a/ethereum/javascript_console.go b/ethereum/javascript_console.go index a6449af8f..9adf51bcc 100644 --- a/ethereum/javascript_console.go +++ b/ethereum/javascript_console.go @@ -21,7 +21,7 @@ func NewJSConsole(ethereum *eth.Ethereum) *JSConsole { func (self *JSConsole) Start() { self.initBindings() - fmt.Println("Eth JS Console") + fmt.Println("Eth JavaScript console") reader := bufio.NewReader(os.Stdin) for { fmt.Printf("eth >>> ") @@ -29,16 +29,18 @@ func (self *JSConsole) Start() { if err != nil { fmt.Println("Error reading input", err) } else { - if string(str) == "quit" { - return - } - self.ParseInput(string(str)) } } } func (self *JSConsole) ParseInput(code string) { + defer func() { + if r := recover(); r != nil { + fmt.Println("[native] error", r) + } + }() + value, err := self.vm.Run(code) if err != nil { fmt.Println(err) @@ -48,29 +50,59 @@ func (self *JSConsole) ParseInput(code string) { fmt.Println(value) } -type OtherStruct struct { - Test string +func (self *JSConsole) initBindings() { + t := &JSWrapper{self.lib, self.vm} + + self.vm.Set("eth", t) } +// The JS wrapper attempts to wrap the PEthereum object and returns +// proper javascript objects type JSWrapper struct { - pub *ethpub.PEthereum - vm *otto.Otto + *ethpub.PEthereum + vm *otto.Otto } func (self *JSWrapper) GetKey() otto.Value { - result, err := self.vm.ToValue(self.pub.GetKey()) + return self.toVal(self.PEthereum.GetKey()) +} + +func (self *JSWrapper) GetStateObject(addr string) otto.Value { + return self.toVal(self.PEthereum.GetStateObject(addr)) +} + +func (self *JSWrapper) Transact(key, recipient, valueStr, gasStr, gasPriceStr, dataStr string) otto.Value { + r, err := self.PEthereum.Transact(key, recipient, valueStr, gasStr, gasPriceStr, dataStr) if err != nil { fmt.Println(err) return otto.UndefinedValue() } - return result + return self.toVal(r) +} +func (self *JSWrapper) Create(key, valueStr, gasStr, gasPriceStr, initStr, bodyStr string) otto.Value { + r, err := self.PEthereum.Create(key, valueStr, gasStr, gasPriceStr, initStr, bodyStr) + + if err != nil { + fmt.Println(err) + + return otto.UndefinedValue() + } + + return self.toVal(r) } -func (self *JSConsole) initBindings() { - t := &JSWrapper{self.lib, self.vm} +// Wrapper function +func (self *JSWrapper) toVal(v interface{}) otto.Value { + result, err := self.vm.ToValue(v) - self.vm.Set("eth", t) + if err != nil { + fmt.Println(err) + + return otto.UndefinedValue() + } + + return result } -- cgit v1.2.3 From 6a78e080e645753ffe3e3bef0b09e71a2469c564 Mon Sep 17 00:00:00 2001 From: obscuren Date: Thu, 15 May 2014 22:17:09 +0200 Subject: Tell config which loggers to use --- ethereum/config.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'ethereum') diff --git a/ethereum/config.go b/ethereum/config.go index 4d7ea6310..5ddc8e635 100644 --- a/ethereum/config.go +++ b/ethereum/config.go @@ -20,7 +20,7 @@ var ExportKey bool var LogFile string var DataDir string var NonInteractive bool -var StartExp bool +var StartJsConsole bool func Init() { flag.BoolVar(&StartConsole, "c", false, "debug and testing console") @@ -39,7 +39,7 @@ func Init() { flag.StringVar(&DataDir, "dir", ".ethereum", "ethereum data directory") flag.StringVar(&ImportKey, "import", "", "imports the given private key (hex)") flag.IntVar(&MaxPeer, "x", 5, "maximum desired peers") - flag.BoolVar(&StartExp, "ex", false, "exp") + flag.BoolVar(&StartJsConsole, "js", false, "exp") flag.Parse() } -- 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 --- ethereum/ethereum.go | 4 +-- ethereum/javascript_console.go | 71 ++++++++++++++++++++++-------------------- ethereum/repl_darwin.go | 55 ++++++++++++++++++++++++++++++++ ethereum/repl_linux.go | 1 + ethereum/repl_windows.go | 20 ++++++++++++ 5 files changed, 116 insertions(+), 35 deletions(-) create mode 100644 ethereum/repl_darwin.go create mode 120000 ethereum/repl_linux.go create mode 100644 ethereum/repl_windows.go (limited to 'ethereum') diff --git a/ethereum/ethereum.go b/ethereum/ethereum.go index 128e11139..04933ef8e 100644 --- a/ethereum/ethereum.go +++ b/ethereum/ethereum.go @@ -151,9 +151,9 @@ save these words so you can restore your account later: %s console := NewConsole(ethereum) go console.Start() } else if StartJsConsole { - c := NewJSConsole(ethereum) + repl := NewJSRepl(ethereum) - go c.Start() + go repl.Start() } if StartRpc { diff --git a/ethereum/javascript_console.go b/ethereum/javascript_console.go index 9adf51bcc..9a10ca236 100644 --- a/ethereum/javascript_console.go +++ b/ethereum/javascript_console.go @@ -1,47 +1,58 @@ package main import ( - "bufio" "fmt" "github.com/ethereum/eth-go" "github.com/ethereum/eth-go/ethpub" "github.com/robertkrimen/otto" - "os" ) -type JSConsole struct { +type Repl interface { + Start() +} + +type JSRE struct { vm *otto.Otto lib *ethpub.PEthereum } -func NewJSConsole(ethereum *eth.Ethereum) *JSConsole { - return &JSConsole{vm: otto.New(), lib: ethpub.NewPEthereum(ethereum)} +func NewJSRE(ethereum *eth.Ethereum) *JSRE { + re := &JSRE{vm: otto.New(), lib: ethpub.NewPEthereum(ethereum)} + + re.Bind("eth", &JSEthereum{re.lib, re.vm}) + + return re +} + +func (self *JSRE) Bind(name string, v interface{}) { + self.vm.Set(name, v) +} + +func (self *JSRE) Run(code string) (otto.Value, error) { + return self.vm.Run(code) } -func (self *JSConsole) Start() { - self.initBindings() +type JSRepl struct { + re *JSRE +} + +func NewJSRepl(ethereum *eth.Ethereum) *JSRepl { + return &JSRepl{re: NewJSRE(ethereum)} +} +func (self *JSRepl) Start() { fmt.Println("Eth JavaScript console") - reader := bufio.NewReader(os.Stdin) - for { - fmt.Printf("eth >>> ") - str, _, err := reader.ReadLine() - if err != nil { - fmt.Println("Error reading input", err) - } else { - self.ParseInput(string(str)) - } - } + self.read() } -func (self *JSConsole) ParseInput(code string) { +func (self *JSRepl) parseInput(code string) { defer func() { if r := recover(); r != nil { fmt.Println("[native] error", r) } }() - value, err := self.vm.Run(code) + value, err := self.re.Run(code) if err != nil { fmt.Println(err) return @@ -50,28 +61,22 @@ func (self *JSConsole) ParseInput(code string) { fmt.Println(value) } -func (self *JSConsole) initBindings() { - t := &JSWrapper{self.lib, self.vm} - - self.vm.Set("eth", t) -} - -// The JS wrapper attempts to wrap the PEthereum object and returns -// proper javascript objects -type JSWrapper struct { +// The JSEthereum object attempts to wrap the PEthereum object and returns +// meaningful javascript objects +type JSEthereum struct { *ethpub.PEthereum vm *otto.Otto } -func (self *JSWrapper) GetKey() otto.Value { +func (self *JSEthereum) GetKey() otto.Value { return self.toVal(self.PEthereum.GetKey()) } -func (self *JSWrapper) GetStateObject(addr string) otto.Value { +func (self *JSEthereum) GetStateObject(addr string) otto.Value { return self.toVal(self.PEthereum.GetStateObject(addr)) } -func (self *JSWrapper) Transact(key, recipient, valueStr, gasStr, gasPriceStr, dataStr string) otto.Value { +func (self *JSEthereum) Transact(key, recipient, valueStr, gasStr, gasPriceStr, dataStr string) otto.Value { r, err := self.PEthereum.Transact(key, recipient, valueStr, gasStr, gasPriceStr, dataStr) if err != nil { fmt.Println(err) @@ -82,7 +87,7 @@ func (self *JSWrapper) Transact(key, recipient, valueStr, gasStr, gasPriceStr, d return self.toVal(r) } -func (self *JSWrapper) Create(key, valueStr, gasStr, gasPriceStr, initStr, bodyStr string) otto.Value { +func (self *JSEthereum) Create(key, valueStr, gasStr, gasPriceStr, initStr, bodyStr string) otto.Value { r, err := self.PEthereum.Create(key, valueStr, gasStr, gasPriceStr, initStr, bodyStr) if err != nil { @@ -95,7 +100,7 @@ func (self *JSWrapper) Create(key, valueStr, gasStr, gasPriceStr, initStr, bodyS } // Wrapper function -func (self *JSWrapper) toVal(v interface{}) otto.Value { +func (self *JSEthereum) toVal(v interface{}) otto.Value { result, err := self.vm.ToValue(v) if err != nil { diff --git a/ethereum/repl_darwin.go b/ethereum/repl_darwin.go new file mode 100644 index 000000000..b6de190e4 --- /dev/null +++ b/ethereum/repl_darwin.go @@ -0,0 +1,55 @@ +package main + +// #cgo LDFLAGS: -lreadline +// #include +// #include +// #include +// #include +import "C" +import "unsafe" + +func readLine(prompt *string) *string { + var p *C.char + + //readline allows an empty prompt(NULL) + if prompt != nil { + p = C.CString(*prompt) + } + + ret := C.readline(p) + + if p != nil { + C.free(unsafe.Pointer(p)) + } + + if ret == nil { + return nil + } //EOF + + s := C.GoString(ret) + C.free(unsafe.Pointer(ret)) + return &s +} + +func addHistory(s string) { + p := C.CString(s) + C.add_history(p) + C.free(unsafe.Pointer(p)) +} + +func (self *JSRepl) read() { + prompt := "eth >>> " + +L: + for { + switch result := readLine(&prompt); true { + case result == nil: + break L //exit loop + + case *result != "": //ignore blank lines + addHistory(*result) //allow user to recall this line + + self.parseInput(*result) + } + } +} diff --git a/ethereum/repl_linux.go b/ethereum/repl_linux.go new file mode 120000 index 000000000..276f135d7 --- /dev/null +++ b/ethereum/repl_linux.go @@ -0,0 +1 @@ +repl_darwin.go \ No newline at end of file diff --git a/ethereum/repl_windows.go b/ethereum/repl_windows.go new file mode 100644 index 000000000..c65bb1cb4 --- /dev/null +++ b/ethereum/repl_windows.go @@ -0,0 +1,20 @@ +package main + +import ( + "bufio" + "fmt" + "os" +) + +func (self *JSRepl) read() { + reader := bufio.NewReader(os.Stdin) + for { + fmt.Printf("eth >>> ") + str, _, err := reader.ReadLine() + if err != nil { + fmt.Println("Error reading input", err) + } else { + self.parseInput(string(str)) + } + } +} -- cgit v1.2.3 From 3b7707c3fd2f99ee1019b8214cba1784af519f53 Mon Sep 17 00:00:00 2001 From: obscuren Date: Mon, 19 May 2014 12:15:03 +0200 Subject: Improved console * Added watch --- ethereum/javascript_console.go | 74 +++++++++++++++++++++++++++++++++++++++--- 1 file changed, 70 insertions(+), 4 deletions(-) (limited to 'ethereum') diff --git a/ethereum/javascript_console.go b/ethereum/javascript_console.go index 9a10ca236..884b9a629 100644 --- a/ethereum/javascript_console.go +++ b/ethereum/javascript_console.go @@ -3,7 +3,9 @@ package main import ( "fmt" "github.com/ethereum/eth-go" + "github.com/ethereum/eth-go/ethchain" "github.com/ethereum/eth-go/ethpub" + "github.com/ethereum/eth-go/ethutil" "github.com/robertkrimen/otto" ) @@ -12,18 +14,83 @@ type Repl interface { } type JSRE struct { - vm *otto.Otto - lib *ethpub.PEthereum + ethereum *eth.Ethereum + vm *otto.Otto + lib *ethpub.PEthereum + + blockChan chan ethutil.React + changeChan chan ethutil.React + quitChan chan bool + + objectCb map[string][]otto.Value } func NewJSRE(ethereum *eth.Ethereum) *JSRE { - re := &JSRE{vm: otto.New(), lib: ethpub.NewPEthereum(ethereum)} + re := &JSRE{ + ethereum, + otto.New(), + ethpub.NewPEthereum(ethereum), + make(chan ethutil.React, 1), + make(chan ethutil.React, 1), + make(chan bool), + make(map[string][]otto.Value), + } + + // We have to make sure that, whoever calls this, calls "Stop" + go re.mainLoop() re.Bind("eth", &JSEthereum{re.lib, re.vm}) + t, _ := re.vm.Get("eth") + t.Object().Set("watch", func(call otto.FunctionCall) otto.Value { + addr, _ := call.Argument(0).ToString() + cb := call.Argument(1) + + re.objectCb[addr] = append(re.objectCb[addr], cb) + + event := "object:" + string(ethutil.FromHex(addr)) + ethereum.Reactor().Subscribe(event, re.changeChan) + + return otto.UndefinedValue() + }) return re } +func (self *JSRE) Stop() { + // Kill the main loop + self.quitChan <- true + + close(self.blockChan) + close(self.quitChan) + close(self.changeChan) +} + +func (self *JSRE) mainLoop() { + // Subscribe to events + reactor := self.ethereum.Reactor() + reactor.Subscribe("newBlock", self.blockChan) + +out: + for { + select { + case <-self.quitChan: + break out + case block := <-self.blockChan: + if _, ok := block.Resource.(*ethchain.Block); ok { + } + case object := <-self.changeChan: + if stateObject, ok := object.Resource.(*ethchain.StateObject); ok { + for _, cb := range self.objectCb[ethutil.Hex(stateObject.Address())] { + val, _ := self.vm.ToValue(ethpub.NewPStateObject(stateObject)) + cb.Call(cb, val) + } + } else if storageObject, ok := object.Resource.(*ethchain.StorageState); ok { + fmt.Println(storageObject) + } + } + } +} + func (self *JSRE) Bind(name string, v interface{}) { self.vm.Set(name, v) } @@ -99,7 +166,6 @@ func (self *JSEthereum) Create(key, valueStr, gasStr, gasPriceStr, initStr, body return self.toVal(r) } -// Wrapper function func (self *JSEthereum) toVal(v interface{}) otto.Value { result, err := self.vm.ToValue(v) -- cgit v1.2.3 From 16421106d47efb65331ed9f0499f12038158cbf1 Mon Sep 17 00:00:00 2001 From: obscuren Date: Mon, 19 May 2014 13:04:31 +0200 Subject: Added multi-line support --- ethereum/javascript_console.go | 5 +++-- ethereum/repl_darwin.go | 37 +++++++++++++++++++++++++++++++------ ethereum/repl_windows.go | 2 +- 3 files changed, 35 insertions(+), 9 deletions(-) (limited to 'ethereum') diff --git a/ethereum/javascript_console.go b/ethereum/javascript_console.go index 884b9a629..1e1ae0e48 100644 --- a/ethereum/javascript_console.go +++ b/ethereum/javascript_console.go @@ -101,14 +101,15 @@ func (self *JSRE) Run(code string) (otto.Value, error) { type JSRepl struct { re *JSRE + + prompt string } func NewJSRepl(ethereum *eth.Ethereum) *JSRepl { - return &JSRepl{re: NewJSRE(ethereum)} + return &JSRepl{re: NewJSRE(ethereum), prompt: "> "} } func (self *JSRepl) Start() { - fmt.Println("Eth JavaScript console") self.read() } diff --git a/ethereum/repl_darwin.go b/ethereum/repl_darwin.go index b6de190e4..483d4cedf 100644 --- a/ethereum/repl_darwin.go +++ b/ethereum/repl_darwin.go @@ -6,7 +6,11 @@ package main // #include // #include import "C" -import "unsafe" + +import ( + "strings" + "unsafe" +) func readLine(prompt *string) *string { var p *C.char @@ -37,19 +41,40 @@ func addHistory(s string) { C.free(unsafe.Pointer(p)) } -func (self *JSRepl) read() { - prompt := "eth >>> " +var indentCount = 0 +var str = "" + +func (self *JSRepl) setIndent() { + open := strings.Count(str, "{") + open += strings.Count(str, "(") + closed := strings.Count(str, "}") + closed += strings.Count(str, ")") + indentCount = open - closed + if indentCount <= 0 { + self.prompt = "> " + } else { + self.prompt = strings.Join(make([]string, indentCount*2), "..") + self.prompt += " " + } +} +func (self *JSRepl) read() { L: for { - switch result := readLine(&prompt); true { + switch result := readLine(&self.prompt); true { case result == nil: break L //exit loop case *result != "": //ignore blank lines - addHistory(*result) //allow user to recall this line + str += *result + "\n" + + self.setIndent() + + if indentCount <= 0 { + addHistory(str) //allow user to recall this line - self.parseInput(*result) + self.parseInput(str) + } } } } diff --git a/ethereum/repl_windows.go b/ethereum/repl_windows.go index c65bb1cb4..c42fd6e6a 100644 --- a/ethereum/repl_windows.go +++ b/ethereum/repl_windows.go @@ -9,7 +9,7 @@ import ( func (self *JSRepl) read() { reader := bufio.NewReader(os.Stdin) for { - fmt.Printf("eth >>> ") + fmt.Printf(self.prompt) str, _, err := reader.ReadLine() if err != nil { fmt.Println("Error reading input", err) -- cgit v1.2.3 From 017bbbb582b09a3264b4ff996f35275d381f284f Mon Sep 17 00:00:00 2001 From: obscuren Date: Mon, 19 May 2014 16:32:45 +0200 Subject: Improved REPL output --- ethereum/ethereum.go | 24 +++++++++++++--------- ethereum/javascript_console.go | 10 ++++++++- ethereum/js_lib.go | 46 ++++++++++++++++++++++++++++++++++++++++++ ethereum/repl_darwin.go | 17 ++++++++++++++-- ethereum/repl_windows.go | 4 ++++ 5 files changed, 89 insertions(+), 12 deletions(-) create mode 100644 ethereum/js_lib.go (limited to 'ethereum') diff --git a/ethereum/ethereum.go b/ethereum/ethereum.go index 04933ef8e..1cbb61002 100644 --- a/ethereum/ethereum.go +++ b/ethereum/ethereum.go @@ -15,16 +15,15 @@ import ( const Debug = true -// Register interrupt handlers so we can stop the ethereum -func RegisterInterrupts(s *eth.Ethereum) { - // Buffered chan of one is enough - c := make(chan os.Signal, 1) - // Notify about interrupts for now - signal.Notify(c, os.Interrupt) +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 { - fmt.Printf("Shutting down (%v) ... \n", sig) - s.Stop() + cb(sig) } }() } @@ -154,13 +153,20 @@ save these words so you can restore your account later: %s repl := NewJSRepl(ethereum) go repl.Start() + + RegisterInterrupt(func(os.Signal) { + repl.Stop() + }) } if StartRpc { utils.DoRpc(ethereum, RpcPort) } - RegisterInterrupts(ethereum) + RegisterInterrupt(func(sig os.Signal) { + fmt.Printf("Shutting down (%v) ... \n", sig) + ethereum.Stop() + }) ethereum.Start(UseSeed) diff --git a/ethereum/javascript_console.go b/ethereum/javascript_console.go index 1e1ae0e48..07d69dafc 100644 --- a/ethereum/javascript_console.go +++ b/ethereum/javascript_console.go @@ -11,6 +11,7 @@ import ( type Repl interface { Start() + Stop() } type JSRE struct { @@ -36,6 +37,9 @@ func NewJSRE(ethereum *eth.Ethereum) *JSRE { make(map[string][]otto.Value), } + // Init the JS lib + re.vm.Run(jsLib) + // We have to make sure that, whoever calls this, calls "Stop" go re.mainLoop() @@ -113,6 +117,10 @@ func (self *JSRepl) Start() { self.read() } +func (self *JSRepl) Stop() { + self.re.Stop() +} + func (self *JSRepl) parseInput(code string) { defer func() { if r := recover(); r != nil { @@ -126,7 +134,7 @@ func (self *JSRepl) parseInput(code string) { return } - fmt.Println(value) + self.PrintValue(value) } // The JSEthereum object attempts to wrap the PEthereum object and returns diff --git a/ethereum/js_lib.go b/ethereum/js_lib.go new file mode 100644 index 000000000..8b59d75ca --- /dev/null +++ b/ethereum/js_lib.go @@ -0,0 +1,46 @@ +package main + +const jsLib = ` +function pp(object) { + var str = ""; + + if(object instanceof Array) { + str += "[ "; + for(var i = 0, l = object.length; i < l; i++) { + str += pp(object[i]); + + if(i < l-1) { + str += ", "; + } + } + str += " ]"; + } else if(typeof(object) === "object") { + str += "{ "; + var last = Object.keys(object).sort().pop() + for(var k in object) { + str += k + ": " + pp(object[k]); + + if(k !== last) { + str += ", "; + } + } + str += " }"; + } else if(typeof(object) === "string") { + str += "\033[32m'" + object + "'"; + } else if(typeof(object) === "undefined") { + str += "\033[1m\033[30m" + object; + } else if(typeof(object) === "number") { + str += "\033[31m" + object; + } else { + str += object; + } + + str += "\033[0m"; + + return str; +} + +function prettyPrint(object) { + console.log(pp(object)) +} +` diff --git a/ethereum/repl_darwin.go b/ethereum/repl_darwin.go index 483d4cedf..87da3df1d 100644 --- a/ethereum/repl_darwin.go +++ b/ethereum/repl_darwin.go @@ -8,6 +8,7 @@ package main import "C" import ( + "github.com/robertkrimen/otto" "strings" "unsafe" ) @@ -63,18 +64,30 @@ L: for { switch result := readLine(&self.prompt); true { case result == nil: - break L //exit loop + break L - case *result != "": //ignore blank lines + case *result != "": str += *result + "\n" self.setIndent() if indentCount <= 0 { + if *result == "exit" { + self.Stop() + break L + } + addHistory(str) //allow user to recall this line self.parseInput(str) + + str = "" } } } } + +func (self *JSRepl) PrintValue(value otto.Value) { + method, _ := self.re.vm.Get("prettyPrint") + method.Call(method, value) +} diff --git a/ethereum/repl_windows.go b/ethereum/repl_windows.go index c42fd6e6a..9d4787772 100644 --- a/ethereum/repl_windows.go +++ b/ethereum/repl_windows.go @@ -18,3 +18,7 @@ func (self *JSRepl) read() { } } } + +func (self *JSRepl) PrintValue(value otto.Value) { + fmt.Println(value) +} -- cgit v1.2.3 From 92eaa98e8381bef5224ffe864aa1cd4288af4d12 Mon Sep 17 00:00:00 2001 From: obscuren Date: Mon, 19 May 2014 17:01:40 +0200 Subject: Added js interpret mode --- ethereum/config.go | 2 ++ ethereum/ethereum.go | 19 ++++++++++++++++++- ethereum/js_lib.go | 11 +++++++++-- 3 files changed, 29 insertions(+), 3 deletions(-) (limited to 'ethereum') diff --git a/ethereum/config.go b/ethereum/config.go index 5ddc8e635..090c022b0 100644 --- a/ethereum/config.go +++ b/ethereum/config.go @@ -21,6 +21,7 @@ var LogFile string var DataDir string var NonInteractive bool var StartJsConsole bool +var InputFile string func Init() { flag.BoolVar(&StartConsole, "c", false, "debug and testing console") @@ -40,6 +41,7 @@ func Init() { flag.StringVar(&ImportKey, "import", "", "imports the given private key (hex)") flag.IntVar(&MaxPeer, "x", 5, "maximum desired peers") flag.BoolVar(&StartJsConsole, "js", false, "exp") + flag.StringVar(&InputFile, "e", "", "Run javascript file") flag.Parse() } diff --git a/ethereum/ethereum.go b/ethereum/ethereum.go index 1cbb61002..f680b5416 100644 --- a/ethereum/ethereum.go +++ b/ethereum/ethereum.go @@ -6,6 +6,7 @@ import ( "github.com/ethereum/eth-go/ethchain" "github.com/ethereum/eth-go/ethutil" "github.com/ethereum/go-ethereum/utils" + "io/ioutil" "log" "os" "os/signal" @@ -51,7 +52,7 @@ func main() { var logSys *log.Logger flags := log.LstdFlags - if StartJsConsole { + if StartJsConsole || len(InputFile) > 0 { ethutil.ReadConfig(DataDir, ethutil.LogFile) } else { ethutil.ReadConfig(DataDir, ethutil.LogFile|ethutil.LogStd) @@ -157,6 +158,22 @@ save these words so you can restore your account later: %s RegisterInterrupt(func(os.Signal) { repl.Stop() }) + } else if len(InputFile) > 0 { + file, err := os.Open(InputFile) + if err != nil { + ethutil.Config.Log.Fatal(err) + } + + content, err := ioutil.ReadAll(file) + if err != nil { + ethutil.Config.Log.Fatal(err) + } + + re := NewJSRE(ethereum) + RegisterInterrupt(func(os.Signal) { + re.Stop() + }) + re.Run(string(content)) } if StartRpc { diff --git a/ethereum/js_lib.go b/ethereum/js_lib.go index 8b59d75ca..189dcc3a0 100644 --- a/ethereum/js_lib.go +++ b/ethereum/js_lib.go @@ -31,6 +31,8 @@ function pp(object) { str += "\033[1m\033[30m" + object; } else if(typeof(object) === "number") { str += "\033[31m" + object; + } else if(typeof(object) === "function") { + str += "\033[35m[Function]"; } else { str += object; } @@ -40,7 +42,12 @@ function pp(object) { return str; } -function prettyPrint(object) { - console.log(pp(object)) +function prettyPrint(/* */) { + var args = arguments; + for(var i = 0, l = args.length; i < l; i++) { + console.log(pp(args[i])) + } } + +var print = prettyPrint; ` -- cgit v1.2.3 From dfc3cb441bed85728914f5575a86c9fcb1f61211 Mon Sep 17 00:00:00 2001 From: Maran Date: Tue, 20 May 2014 11:52:36 +0200 Subject: Increase default peer amount to 10 --- ethereum/config.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'ethereum') diff --git a/ethereum/config.go b/ethereum/config.go index 090c022b0..117aa6f2c 100644 --- a/ethereum/config.go +++ b/ethereum/config.go @@ -39,7 +39,7 @@ func Init() { flag.StringVar(&LogFile, "logfile", "", "log file (defaults to standard output)") flag.StringVar(&DataDir, "dir", ".ethereum", "ethereum data directory") flag.StringVar(&ImportKey, "import", "", "imports the given private key (hex)") - flag.IntVar(&MaxPeer, "x", 5, "maximum desired peers") + flag.IntVar(&MaxPeer, "x", 10, "maximum desired peers") flag.BoolVar(&StartJsConsole, "js", false, "exp") flag.StringVar(&InputFile, "e", "", "Run javascript file") -- cgit v1.2.3 From a05adb11288a1ea9dc6e38a952ab89fa5eb7f794 Mon Sep 17 00:00:00 2001 From: obscuren Date: Tue, 20 May 2014 12:48:34 +0200 Subject: Refactored file structure --- ethereum/javascript_console.go | 188 ----------------------------------------- ethereum/javascript_runtime.go | 114 +++++++++++++++++++++++++ ethereum/repl.go | 97 +++++++++++++++++++++ 3 files changed, 211 insertions(+), 188 deletions(-) delete mode 100644 ethereum/javascript_console.go create mode 100644 ethereum/javascript_runtime.go create mode 100644 ethereum/repl.go (limited to 'ethereum') diff --git a/ethereum/javascript_console.go b/ethereum/javascript_console.go deleted file mode 100644 index 07d69dafc..000000000 --- a/ethereum/javascript_console.go +++ /dev/null @@ -1,188 +0,0 @@ -package main - -import ( - "fmt" - "github.com/ethereum/eth-go" - "github.com/ethereum/eth-go/ethchain" - "github.com/ethereum/eth-go/ethpub" - "github.com/ethereum/eth-go/ethutil" - "github.com/robertkrimen/otto" -) - -type Repl interface { - Start() - Stop() -} - -type JSRE struct { - ethereum *eth.Ethereum - vm *otto.Otto - lib *ethpub.PEthereum - - blockChan chan ethutil.React - changeChan chan ethutil.React - quitChan chan bool - - objectCb map[string][]otto.Value -} - -func NewJSRE(ethereum *eth.Ethereum) *JSRE { - re := &JSRE{ - ethereum, - otto.New(), - ethpub.NewPEthereum(ethereum), - make(chan ethutil.React, 1), - make(chan ethutil.React, 1), - make(chan bool), - make(map[string][]otto.Value), - } - - // Init the JS lib - re.vm.Run(jsLib) - - // We have to make sure that, whoever calls this, calls "Stop" - go re.mainLoop() - - re.Bind("eth", &JSEthereum{re.lib, re.vm}) - t, _ := re.vm.Get("eth") - t.Object().Set("watch", func(call otto.FunctionCall) otto.Value { - addr, _ := call.Argument(0).ToString() - cb := call.Argument(1) - - re.objectCb[addr] = append(re.objectCb[addr], cb) - - event := "object:" + string(ethutil.FromHex(addr)) - ethereum.Reactor().Subscribe(event, re.changeChan) - - return otto.UndefinedValue() - }) - - return re -} - -func (self *JSRE) Stop() { - // Kill the main loop - self.quitChan <- true - - close(self.blockChan) - close(self.quitChan) - close(self.changeChan) -} - -func (self *JSRE) mainLoop() { - // Subscribe to events - reactor := self.ethereum.Reactor() - reactor.Subscribe("newBlock", self.blockChan) - -out: - for { - select { - case <-self.quitChan: - break out - case block := <-self.blockChan: - if _, ok := block.Resource.(*ethchain.Block); ok { - } - case object := <-self.changeChan: - if stateObject, ok := object.Resource.(*ethchain.StateObject); ok { - for _, cb := range self.objectCb[ethutil.Hex(stateObject.Address())] { - val, _ := self.vm.ToValue(ethpub.NewPStateObject(stateObject)) - cb.Call(cb, val) - } - } else if storageObject, ok := object.Resource.(*ethchain.StorageState); ok { - fmt.Println(storageObject) - } - } - } -} - -func (self *JSRE) Bind(name string, v interface{}) { - self.vm.Set(name, v) -} - -func (self *JSRE) Run(code string) (otto.Value, error) { - return self.vm.Run(code) -} - -type JSRepl struct { - re *JSRE - - prompt string -} - -func NewJSRepl(ethereum *eth.Ethereum) *JSRepl { - return &JSRepl{re: NewJSRE(ethereum), prompt: "> "} -} - -func (self *JSRepl) Start() { - self.read() -} - -func (self *JSRepl) Stop() { - self.re.Stop() -} - -func (self *JSRepl) parseInput(code string) { - defer func() { - if r := recover(); r != nil { - fmt.Println("[native] error", r) - } - }() - - value, err := self.re.Run(code) - if err != nil { - fmt.Println(err) - return - } - - self.PrintValue(value) -} - -// The JSEthereum object attempts to wrap the PEthereum object and returns -// meaningful javascript objects -type JSEthereum struct { - *ethpub.PEthereum - vm *otto.Otto -} - -func (self *JSEthereum) GetKey() otto.Value { - return self.toVal(self.PEthereum.GetKey()) -} - -func (self *JSEthereum) GetStateObject(addr string) otto.Value { - return self.toVal(self.PEthereum.GetStateObject(addr)) -} - -func (self *JSEthereum) Transact(key, recipient, valueStr, gasStr, gasPriceStr, dataStr string) otto.Value { - r, err := self.PEthereum.Transact(key, recipient, valueStr, gasStr, gasPriceStr, dataStr) - if err != nil { - fmt.Println(err) - - return otto.UndefinedValue() - } - - return self.toVal(r) -} - -func (self *JSEthereum) Create(key, valueStr, gasStr, gasPriceStr, initStr, bodyStr string) otto.Value { - r, err := self.PEthereum.Create(key, valueStr, gasStr, gasPriceStr, initStr, bodyStr) - - if err != nil { - fmt.Println(err) - - return otto.UndefinedValue() - } - - return self.toVal(r) -} - -func (self *JSEthereum) toVal(v interface{}) otto.Value { - result, err := self.vm.ToValue(v) - - if err != nil { - fmt.Println(err) - - return otto.UndefinedValue() - } - - return result -} diff --git a/ethereum/javascript_runtime.go b/ethereum/javascript_runtime.go new file mode 100644 index 000000000..b06fb9460 --- /dev/null +++ b/ethereum/javascript_runtime.go @@ -0,0 +1,114 @@ +package main + +import ( + "fmt" + "github.com/ethereum/eth-go" + "github.com/ethereum/eth-go/ethchain" + "github.com/ethereum/eth-go/ethpub" + "github.com/ethereum/eth-go/ethutil" + "github.com/robertkrimen/otto" +) + +type JSRE struct { + ethereum *eth.Ethereum + vm *otto.Otto + lib *ethpub.PEthereum + + blockChan chan ethutil.React + changeChan chan ethutil.React + quitChan chan bool + + objectCb map[string][]otto.Value +} + +func NewJSRE(ethereum *eth.Ethereum) *JSRE { + re := &JSRE{ + ethereum, + otto.New(), + ethpub.NewPEthereum(ethereum), + make(chan ethutil.React, 1), + make(chan ethutil.React, 1), + make(chan bool), + make(map[string][]otto.Value), + } + + // Init the JS lib + re.vm.Run(jsLib) + + // We have to make sure that, whoever calls this, calls "Stop" + go re.mainLoop() + + re.Bind("eth", &JSEthereum{re.lib, re.vm}) + + re.initStdFuncs() + + return re +} + +func (self *JSRE) Bind(name string, v interface{}) { + self.vm.Set(name, v) +} + +func (self *JSRE) Run(code string) (otto.Value, error) { + return self.vm.Run(code) +} + +func (self *JSRE) Stop() { + // Kill the main loop + self.quitChan <- true + + close(self.blockChan) + close(self.quitChan) + close(self.changeChan) +} + +func (self *JSRE) mainLoop() { + // Subscribe to events + reactor := self.ethereum.Reactor() + reactor.Subscribe("newBlock", self.blockChan) + +out: + for { + select { + case <-self.quitChan: + break out + case block := <-self.blockChan: + if _, ok := block.Resource.(*ethchain.Block); ok { + } + case object := <-self.changeChan: + if stateObject, ok := object.Resource.(*ethchain.StateObject); ok { + for _, cb := range self.objectCb[ethutil.Hex(stateObject.Address())] { + val, _ := self.vm.ToValue(ethpub.NewPStateObject(stateObject)) + cb.Call(cb, val) + } + } else if storageObject, ok := object.Resource.(*ethchain.StorageState); ok { + fmt.Println(storageObject) + } + } + } +} + +func (self *JSRE) initStdFuncs() { + t, _ := self.vm.Get("eth") + eth := t.Object() + eth.Set("watch", func(call otto.FunctionCall) otto.Value { + addr, _ := call.Argument(0).ToString() + cb := call.Argument(1) + + self.objectCb[addr] = append(self.objectCb[addr], cb) + + event := "object:" + string(ethutil.FromHex(addr)) + self.ethereum.Reactor().Subscribe(event, self.changeChan) + + return otto.UndefinedValue() + }) + eth.Set("addPeer", func(call otto.FunctionCall) otto.Value { + host, err := call.Argument(0).ToString() + if err != nil { + return otto.FalseValue() + } + self.ethereum.ConnectToPeer(host) + + return otto.TrueValue() + }) +} diff --git a/ethereum/repl.go b/ethereum/repl.go new file mode 100644 index 000000000..c0b63c0a5 --- /dev/null +++ b/ethereum/repl.go @@ -0,0 +1,97 @@ +package main + +import ( + "fmt" + "github.com/ethereum/eth-go" + "github.com/ethereum/eth-go/ethpub" + "github.com/robertkrimen/otto" +) + +type Repl interface { + Start() + Stop() +} + +type JSRepl struct { + re *JSRE + + prompt string +} + +func NewJSRepl(ethereum *eth.Ethereum) *JSRepl { + return &JSRepl{re: NewJSRE(ethereum), prompt: "> "} +} + +func (self *JSRepl) Start() { + self.read() +} + +func (self *JSRepl) Stop() { + self.re.Stop() +} + +func (self *JSRepl) parseInput(code string) { + defer func() { + if r := recover(); r != nil { + fmt.Println("[native] error", r) + } + }() + + value, err := self.re.Run(code) + if err != nil { + fmt.Println(err) + return + } + + self.PrintValue(value) +} + +// The JSEthereum object attempts to wrap the PEthereum object and returns +// meaningful javascript objects +type JSEthereum struct { + *ethpub.PEthereum + vm *otto.Otto +} + +func (self *JSEthereum) GetKey() otto.Value { + return self.toVal(self.PEthereum.GetKey()) +} + +func (self *JSEthereum) GetStateObject(addr string) otto.Value { + return self.toVal(self.PEthereum.GetStateObject(addr)) +} + +func (self *JSEthereum) Transact(key, recipient, valueStr, gasStr, gasPriceStr, dataStr string) otto.Value { + r, err := self.PEthereum.Transact(key, recipient, valueStr, gasStr, gasPriceStr, dataStr) + if err != nil { + fmt.Println(err) + + return otto.UndefinedValue() + } + + return self.toVal(r) +} + +func (self *JSEthereum) Create(key, valueStr, gasStr, gasPriceStr, initStr, bodyStr string) otto.Value { + r, err := self.PEthereum.Create(key, valueStr, gasStr, gasPriceStr, initStr, bodyStr) + + if err != nil { + fmt.Println(err) + + return otto.UndefinedValue() + } + + return self.toVal(r) +} + +func (self *JSEthereum) toVal(v interface{}) otto.Value { + result, err := self.vm.ToValue(v) + + if err != nil { + fmt.Println(err) + + return otto.UndefinedValue() + } + + return result +} -- cgit v1.2.3 From 0ef7f6372939189dcfeaea8197798a63a6d6688a Mon Sep 17 00:00:00 2001 From: obscuren Date: Tue, 20 May 2014 12:57:43 +0200 Subject: Removed old console in favor of the new JS REPL --- ethereum/config.go | 3 - ethereum/dev_console.go | 259 ------------------------------------------------ ethereum/ethereum.go | 11 +- 3 files changed, 1 insertion(+), 272 deletions(-) delete mode 100644 ethereum/dev_console.go (limited to 'ethereum') diff --git a/ethereum/config.go b/ethereum/config.go index 117aa6f2c..97e8687d8 100644 --- a/ethereum/config.go +++ b/ethereum/config.go @@ -4,7 +4,6 @@ import ( "flag" ) -var StartConsole bool var StartMining bool var StartRpc bool var RpcPort int @@ -24,10 +23,8 @@ var StartJsConsole bool var InputFile string func Init() { - flag.BoolVar(&StartConsole, "c", false, "debug and testing console") flag.BoolVar(&StartMining, "m", false, "start dagger mining") flag.BoolVar(&ShowGenesis, "g", false, "prints genesis header and exits") - //flag.BoolVar(&UseGui, "gui", true, "use the gui") flag.BoolVar(&StartRpc, "r", false, "start rpc server") flag.IntVar(&RpcPort, "rpcport", 8080, "port to start json-rpc server on") flag.BoolVar(&NonInteractive, "y", false, "non-interactive mode (say yes to confirmations)") diff --git a/ethereum/dev_console.go b/ethereum/dev_console.go deleted file mode 100644 index 5941c03ab..000000000 --- a/ethereum/dev_console.go +++ /dev/null @@ -1,259 +0,0 @@ -package main - -import ( - "bufio" - "bytes" - "encoding/hex" - "errors" - "fmt" - "github.com/ethereum/eth-go" - "github.com/ethereum/eth-go/ethchain" - "github.com/ethereum/eth-go/ethdb" - "github.com/ethereum/eth-go/ethutil" - "github.com/ethereum/eth-go/ethwire" - "github.com/ethereum/go-ethereum/utils" - "github.com/obscuren/mutan" - "os" - "strings" -) - -type Console struct { - db *ethdb.MemDatabase - trie *ethutil.Trie - ethereum *eth.Ethereum -} - -func NewConsole(s *eth.Ethereum) *Console { - db, _ := ethdb.NewMemDatabase() - trie := ethutil.NewTrie(db, "") - - return &Console{db: db, trie: trie, ethereum: s} -} - -func (i *Console) ValidateInput(action string, argumentLength int) error { - err := false - var expArgCount int - - switch { - case action == "update" && argumentLength != 2: - err = true - expArgCount = 2 - case action == "get" && argumentLength != 1: - err = true - expArgCount = 1 - case action == "dag" && argumentLength != 2: - err = true - expArgCount = 2 - case action == "decode" && argumentLength != 1: - err = true - expArgCount = 1 - case action == "encode" && argumentLength != 1: - err = true - expArgCount = 1 - case action == "gettx" && argumentLength != 1: - err = true - expArgCount = 1 - case action == "tx" && argumentLength != 4: - err = true - expArgCount = 4 - case action == "getaddr" && argumentLength != 1: - err = true - expArgCount = 1 - case action == "contract" && argumentLength != 2: - err = true - expArgCount = 2 - case action == "say" && argumentLength != 1: - err = true - expArgCount = 1 - case action == "addp" && argumentLength != 1: - err = true - expArgCount = 1 - case action == "block" && argumentLength != 1: - err = true - expArgCount = 1 - } - - if err { - return errors.New(fmt.Sprintf("'%s' requires %d args, got %d", action, expArgCount, argumentLength)) - } else { - return nil - } -} - -func (i *Console) Editor() string { - var buff bytes.Buffer - for { - reader := bufio.NewReader(os.Stdin) - str, _, err := reader.ReadLine() - if len(str) > 0 { - buff.Write(str) - buff.WriteString("\n") - } - - if err != nil && err.Error() == "EOF" { - break - } - } - - return buff.String() -} - -func (i *Console) PrintRoot() { - root := ethutil.NewValue(i.trie.Root) - if len(root.Bytes()) != 0 { - fmt.Println(hex.EncodeToString(root.Bytes())) - } else { - fmt.Println(i.trie.Root) - } -} - -func (i *Console) ParseInput(input string) bool { - scanner := bufio.NewScanner(strings.NewReader(input)) - scanner.Split(bufio.ScanWords) - - count := 0 - var tokens []string - for scanner.Scan() { - count++ - tokens = append(tokens, scanner.Text()) - } - if err := scanner.Err(); err != nil { - fmt.Fprintln(os.Stderr, "reading input:", err) - } - - if len(tokens) == 0 { - return true - } - - err := i.ValidateInput(tokens[0], count-1) - if err != nil { - fmt.Println(err) - } else { - switch tokens[0] { - case "update": - i.trie.Update(tokens[1], tokens[2]) - - i.PrintRoot() - case "get": - fmt.Println(i.trie.Get(tokens[1])) - case "root": - i.PrintRoot() - case "rawroot": - fmt.Println(i.trie.Root) - case "print": - i.db.Print() - case "dag": - fmt.Println(ethchain.DaggerVerify(ethutil.Big(tokens[1]), // hash - ethutil.BigPow(2, 36), // diff - ethutil.Big(tokens[2]))) // nonce - case "decode": - value := ethutil.NewValueFromBytes([]byte(tokens[1])) - fmt.Println(value) - case "getaddr": - encoded, _ := hex.DecodeString(tokens[1]) - addr := i.ethereum.BlockChain().CurrentBlock.State().GetAccount(encoded) - fmt.Println("addr:", addr) - case "block": - encoded, _ := hex.DecodeString(tokens[1]) - block := i.ethereum.BlockChain().GetBlock(encoded) - info := block.BlockInfo() - fmt.Printf("++++++++++ #%d ++++++++++\n%v\n", info.Number, block) - case "say": - i.ethereum.Broadcast(ethwire.MsgTalkTy, []interface{}{tokens[1]}) - case "addp": - i.ethereum.ConnectToPeer(tokens[1]) - case "pcount": - fmt.Println("peers:", i.ethereum.Peers().Len()) - case "encode": - fmt.Printf("%q\n", ethutil.Encode(tokens[1])) - case "tx": - recipient, err := hex.DecodeString(tokens[1]) - if err != nil { - fmt.Println("recipient err:", err) - } else { - tx := ethchain.NewTransactionMessage(recipient, ethutil.Big(tokens[2]), ethutil.Big(tokens[3]), ethutil.Big(tokens[4]), nil) - - keyPair := ethutil.GetKeyRing().Get(0) - tx.Sign(keyPair.PrivateKey) - i.ethereum.TxPool().QueueTransaction(tx) - - fmt.Printf("%x\n", tx.Hash()) - } - case "gettx": - addr, _ := hex.DecodeString(tokens[1]) - data, _ := ethutil.Config.Db.Get(addr) - if len(data) != 0 { - decoder := ethutil.NewValueFromBytes(data) - fmt.Println(decoder) - } else { - fmt.Println("gettx: tx not found") - } - case "contract": - fmt.Println("Contract editor (Ctrl-D = done)") - - mainInput, initInput := mutan.PreParse(i.Editor()) - mainScript, err := utils.Compile(mainInput) - if err != nil { - fmt.Println(err) - - break - } - initScript, err := utils.Compile(initInput) - if err != nil { - fmt.Println(err) - - break - } - - contract := ethchain.NewContractCreationTx(ethutil.Big(tokens[0]), ethutil.Big(tokens[1]), ethutil.Big(tokens[1]), mainScript, initScript) - - keyPair := ethutil.GetKeyRing().Get(0) - contract.Sign(keyPair.PrivateKey) - - i.ethereum.TxPool().QueueTransaction(contract) - - fmt.Printf("%x\n", contract.Hash()[12:]) - case "exit", "quit", "q": - return false - case "help": - fmt.Printf("COMMANDS:\n" + - "\033[1m= DB =\033[0m\n" + - "update KEY VALUE - Updates/Creates a new value for the given key\n" + - "get KEY - Retrieves the given key\n" + - "root - Prints the hex encoded merkle root\n" + - "rawroot - Prints the raw merkle root\n" + - "block HASH - Prints the block\n" + - "getaddr ADDR - Prints the account associated with the address\n" + - "\033[1m= Dagger =\033[0m\n" + - "dag HASH NONCE - Verifies a nonce with the given hash with dagger\n" + - "\033[1m= Encoding =\033[0m\n" + - "decode STR\n" + - "encode STR\n" + - "\033[1m= Other =\033[0m\n" + - "addp HOST:PORT\n" + - "tx TO AMOUNT\n" + - "contract AMOUNT\n") - - default: - fmt.Println("Unknown command:", tokens[0]) - } - } - - return true -} - -func (i *Console) Start() { - fmt.Printf("Eth Console. Type (help) for help\n") - reader := bufio.NewReader(os.Stdin) - for { - fmt.Printf("eth >>> ") - str, _, err := reader.ReadLine() - if err != nil { - fmt.Println("Error reading input", err) - } else { - if !i.ParseInput(string(str)) { - return - } - } - } -} diff --git a/ethereum/ethereum.go b/ethereum/ethereum.go index f680b5416..2fdfd5caf 100644 --- a/ethereum/ethereum.go +++ b/ethereum/ethereum.go @@ -141,16 +141,7 @@ save these words so you can restore your account later: %s utils.DoMining(ethereum) } - if StartConsole { - err := os.Mkdir(ethutil.Config.ExecPath, os.ModePerm) - // Error is OK if the error is ErrExist - if err != nil && !os.IsExist(err) { - log.Panic("Unable to create EXECPATH:", err) - } - - console := NewConsole(ethereum) - go console.Start() - } else if StartJsConsole { + if StartJsConsole { repl := NewJSRepl(ethereum) go repl.Start() -- cgit v1.2.3 From de1dfae7170a946d255a9b4932e08f887d48947c Mon Sep 17 00:00:00 2001 From: obscuren Date: Tue, 20 May 2014 17:49:12 +0200 Subject: Forked version of otto so we can support lowerCased methods --- ethereum/javascript_runtime.go | 2 +- ethereum/repl.go | 2 +- ethereum/repl_darwin.go | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) (limited to 'ethereum') diff --git a/ethereum/javascript_runtime.go b/ethereum/javascript_runtime.go index b06fb9460..cc8fe370f 100644 --- a/ethereum/javascript_runtime.go +++ b/ethereum/javascript_runtime.go @@ -6,7 +6,7 @@ import ( "github.com/ethereum/eth-go/ethchain" "github.com/ethereum/eth-go/ethpub" "github.com/ethereum/eth-go/ethutil" - "github.com/robertkrimen/otto" + "github.com/obscuren/otto" ) type JSRE struct { diff --git a/ethereum/repl.go b/ethereum/repl.go index c0b63c0a5..29d38afef 100644 --- a/ethereum/repl.go +++ b/ethereum/repl.go @@ -4,7 +4,7 @@ import ( "fmt" "github.com/ethereum/eth-go" "github.com/ethereum/eth-go/ethpub" - "github.com/robertkrimen/otto" + "github.com/obscuren/otto" ) type Repl interface { diff --git a/ethereum/repl_darwin.go b/ethereum/repl_darwin.go index 87da3df1d..cf6e24e18 100644 --- a/ethereum/repl_darwin.go +++ b/ethereum/repl_darwin.go @@ -8,7 +8,7 @@ package main import "C" import ( - "github.com/robertkrimen/otto" + "github.com/obscuren/otto" "strings" "unsafe" ) -- cgit v1.2.3 From 563c035eb57a0507979a84f3dd22411be2a4cad1 Mon Sep 17 00:00:00 2001 From: obscuren Date: Tue, 20 May 2014 19:28:48 +0200 Subject: Refactored some of the functions --- ethereum/javascript_runtime.go | 89 ++++++++++++++++++++++++++++++++++++------ ethereum/repl_darwin.go | 8 ++-- 2 files changed, 81 insertions(+), 16 deletions(-) (limited to 'ethereum') diff --git a/ethereum/javascript_runtime.go b/ethereum/javascript_runtime.go index cc8fe370f..76ced3f3d 100644 --- a/ethereum/javascript_runtime.go +++ b/ethereum/javascript_runtime.go @@ -7,6 +7,9 @@ import ( "github.com/ethereum/eth-go/ethpub" "github.com/ethereum/eth-go/ethutil" "github.com/obscuren/otto" + "io/ioutil" + "os" + "path/filepath" ) type JSRE struct { @@ -53,6 +56,22 @@ func (self *JSRE) Run(code string) (otto.Value, error) { return self.vm.Run(code) } +func (self *JSRE) Require(file string) error { + if len(filepath.Ext(file)) == 0 { + file += ".js" + } + + fh, err := os.Open(file) + if err != nil { + return err + } + + content, _ := ioutil.ReadAll(fh) + self.Run("exports = {};(function() {" + string(content) + "})();") + + return nil +} + func (self *JSRE) Stop() { // Kill the main loop self.quitChan <- true @@ -82,7 +101,10 @@ out: cb.Call(cb, val) } } else if storageObject, ok := object.Resource.(*ethchain.StorageState); ok { - fmt.Println(storageObject) + for _, cb := range self.objectCb[ethutil.Hex(storageObject.Address)+ethutil.Hex(storageObject.StateAddress)] { + val, _ := self.vm.ToValue(ethpub.NewPStorageState(storageObject)) + cb.Call(cb, val) + } } } } @@ -91,24 +113,65 @@ out: func (self *JSRE) initStdFuncs() { t, _ := self.vm.Get("eth") eth := t.Object() - eth.Set("watch", func(call otto.FunctionCall) otto.Value { - addr, _ := call.Argument(0).ToString() - cb := call.Argument(1) + eth.Set("watch", self.watch) + eth.Set("addPeer", self.addPeer) + self.Set("require", self.require) +} + +/* + * The following methods are natively implemented javascript functions + */ + +// eth.watch +func (self JSRE) watch(call otto.FunctionCall) otto.Value { + addr, _ := call.Argument(0).ToString() + var storageAddr string + var cb otto.Value + var storageCallback bool + if len(call.ArgumentList) > 2 { + storageCallback = true + storageAddr, _ = call.Argument(1).ToString() + cb = call.Argument(2) + } else { + cb = call.Argument(1) + } + + if storageCallback { + self.objectCb[addr+storageAddr] = append(self.objectCb[addr+storageAddr], cb) + event := "storage:" + string(ethutil.FromHex(addr)) + ":" + string(ethutil.FromHex(storageAddr)) + self.ethereum.Reactor().Subscribe(event, self.changeChan) + } else { self.objectCb[addr] = append(self.objectCb[addr], cb) event := "object:" + string(ethutil.FromHex(addr)) self.ethereum.Reactor().Subscribe(event, self.changeChan) + } + + return otto.UndefinedValue() +} +func (self *JSRE) addPeer(call otto.FunctionCall) otto.Value { + host, err := call.Argument(0).ToString() + if err != nil { + return otto.FalseValue() + } + self.ethereum.ConnectToPeer(host) + + return otto.TrueValue() +} + +func (self *JSRE) require(call otto.FunctionCall) otto.Value { + file, err := call.Argument(0).ToString() + if err != nil { return otto.UndefinedValue() - }) - eth.Set("addPeer", func(call otto.FunctionCall) otto.Value { - host, err := call.Argument(0).ToString() - if err != nil { - return otto.FalseValue() - } - self.ethereum.ConnectToPeer(host) + } + if err := self.Require(file); err != nil { + fmt.Println("err:", err) + return otto.UndefinedValue() + } + + t, _ := self.vm.Get("exports") - return otto.TrueValue() - }) + return t } diff --git a/ethereum/repl_darwin.go b/ethereum/repl_darwin.go index cf6e24e18..1b98c2150 100644 --- a/ethereum/repl_darwin.go +++ b/ethereum/repl_darwin.go @@ -8,7 +8,6 @@ package main import "C" import ( - "github.com/obscuren/otto" "strings" "unsafe" ) @@ -87,7 +86,10 @@ L: } } -func (self *JSRepl) PrintValue(value otto.Value) { +func (self *JSRepl) PrintValue(v interface{}) { method, _ := self.re.vm.Get("prettyPrint") - method.Call(method, value) + v, err := self.re.vm.ToValue(v) + if err == nil { + method.Call(method, v) + } } -- cgit v1.2.3 From f4551a7e9f90dd10b22ccfcdaf59d1a6a35283cf Mon Sep 17 00:00:00 2001 From: obscuren Date: Tue, 20 May 2014 22:12:22 +0200 Subject: Changed flag parsing --- ethereum/config.go | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) (limited to 'ethereum') diff --git a/ethereum/config.go b/ethereum/config.go index 97e8687d8..f25f2fb66 100644 --- a/ethereum/config.go +++ b/ethereum/config.go @@ -2,6 +2,8 @@ package main import ( "flag" + "fmt" + "os" ) var StartMining bool @@ -23,6 +25,11 @@ var StartJsConsole bool var InputFile string func Init() { + flag.Usage = func() { + fmt.Fprintf(os.Stderr, "%s [options] [filename]:\n", os.Args[0]) + flag.PrintDefaults() + } + flag.BoolVar(&StartMining, "m", false, "start dagger mining") flag.BoolVar(&ShowGenesis, "g", false, "prints genesis header and exits") flag.BoolVar(&StartRpc, "r", false, "start rpc server") @@ -38,7 +45,9 @@ func Init() { flag.StringVar(&ImportKey, "import", "", "imports the given private key (hex)") flag.IntVar(&MaxPeer, "x", 10, "maximum desired peers") flag.BoolVar(&StartJsConsole, "js", false, "exp") - flag.StringVar(&InputFile, "e", "", "Run javascript file") + //flag.StringVar(&InputFile, "e", "", "Run javascript file") flag.Parse() + + InputFile = flag.Arg(0) } -- cgit v1.2.3 From 93e12250c702521807247a66d74cc0792370d83b Mon Sep 17 00:00:00 2001 From: obscuren Date: Tue, 20 May 2014 22:12:42 +0200 Subject: Switch variables as intended --- ethereum/javascript_runtime.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'ethereum') diff --git a/ethereum/javascript_runtime.go b/ethereum/javascript_runtime.go index 76ced3f3d..fa01c7005 100644 --- a/ethereum/javascript_runtime.go +++ b/ethereum/javascript_runtime.go @@ -101,7 +101,7 @@ out: cb.Call(cb, val) } } else if storageObject, ok := object.Resource.(*ethchain.StorageState); ok { - for _, cb := range self.objectCb[ethutil.Hex(storageObject.Address)+ethutil.Hex(storageObject.StateAddress)] { + for _, cb := range self.objectCb[ethutil.Hex(storageObject.StateAddress)+ethutil.Hex(storageObject.Address)] { val, _ := self.vm.ToValue(ethpub.NewPStorageState(storageObject)) cb.Call(cb, val) } @@ -115,7 +115,7 @@ func (self *JSRE) initStdFuncs() { eth := t.Object() eth.Set("watch", self.watch) eth.Set("addPeer", self.addPeer) - self.Set("require", self.require) + eth.Set("require", self.require) } /* -- cgit v1.2.3 From 16bd88c10ab3553984d180e3048839982c864f69 Mon Sep 17 00:00:00 2001 From: obscuren Date: Wed, 21 May 2014 12:14:39 +0200 Subject: Removed method name --- ethereum/repl.go | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'ethereum') diff --git a/ethereum/repl.go b/ethereum/repl.go index 29d38afef..d1243d19c 100644 --- a/ethereum/repl.go +++ b/ethereum/repl.go @@ -53,6 +53,10 @@ type JSEthereum struct { vm *otto.Otto } +func (self *JSEthereum) GetBlock(hash string) otto.Value { + return self.toVal(self.PEthereum.GetBlock(hash)) +} + func (self *JSEthereum) GetKey() otto.Value { return self.toVal(self.PEthereum.GetKey()) } -- cgit v1.2.3 From 3f5b348451a8acd4c22be1c320808dd4eadc38d3 Mon Sep 17 00:00:00 2001 From: obscuren Date: Wed, 21 May 2014 23:36:55 +0200 Subject: Fixes #50 --- ethereum/repl_darwin.go | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) (limited to 'ethereum') diff --git a/ethereum/repl_darwin.go b/ethereum/repl_darwin.go index 1b98c2150..cb11adfc7 100644 --- a/ethereum/repl_darwin.go +++ b/ethereum/repl_darwin.go @@ -1,17 +1,37 @@ package main +// #cgo darwin CFLAGS: -I/usr/local/opt/readline/include +// #cgo darwin LDFLAGS: -L/usr/local/opt/readline/lib // #cgo LDFLAGS: -lreadline // #include // #include // #include // #include import "C" - import ( + "os" + "os/signal" "strings" + "syscall" "unsafe" ) +func initReadLine() { + C.rl_catch_sigwinch = 0 + c := make(chan os.Signal, 1) + signal.Notify(c, syscall.SIGWINCH) + go func() { + for sig := range c { + switch sig { + case syscall.SIGWINCH: + C.rl_resize_terminal() + default: + + } + } + }() +} + func readLine(prompt *string) *string { var p *C.char @@ -59,6 +79,7 @@ func (self *JSRepl) setIndent() { } func (self *JSRepl) read() { + initReadLine() L: for { switch result := readLine(&self.prompt); true { -- cgit v1.2.3 From b902de20c7119ec521a28bba986a0cc9d14354c0 Mon Sep 17 00:00:00 2001 From: obscuren Date: Wed, 21 May 2014 23:46:16 +0200 Subject: Fixes #49 --- ethereum/repl_darwin.go | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'ethereum') diff --git a/ethereum/repl_darwin.go b/ethereum/repl_darwin.go index cb11adfc7..fa36b0d52 100644 --- a/ethereum/repl_darwin.go +++ b/ethereum/repl_darwin.go @@ -18,13 +18,18 @@ import ( func initReadLine() { C.rl_catch_sigwinch = 0 + C.rl_catch_signals = 0 c := make(chan os.Signal, 1) signal.Notify(c, syscall.SIGWINCH) + signal.Notify(c, os.Interrupt) go func() { for sig := range c { switch sig { case syscall.SIGWINCH: C.rl_resize_terminal() + + case os.Interrupt: + C.rl_cleanup_after_signal() default: } -- 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 --- ethereum/javascript_runtime.go | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) (limited to 'ethereum') diff --git a/ethereum/javascript_runtime.go b/ethereum/javascript_runtime.go index fa01c7005..93297f604 100644 --- a/ethereum/javascript_runtime.go +++ b/ethereum/javascript_runtime.go @@ -6,6 +6,7 @@ import ( "github.com/ethereum/eth-go/ethchain" "github.com/ethereum/eth-go/ethpub" "github.com/ethereum/eth-go/ethutil" + "github.com/ethereum/go-ethereum/utils" "github.com/obscuren/otto" "io/ioutil" "os" @@ -116,14 +117,26 @@ func (self *JSRE) initStdFuncs() { eth.Set("watch", self.watch) eth.Set("addPeer", self.addPeer) eth.Set("require", self.require) + eth.Set("stopMining", self.stopMining) + eth.Set("startMining", self.startMining) } /* * The following methods are natively implemented javascript functions */ +func (self *JSRE) stopMining(call otto.FunctionCall) otto.Value { + v, _ := self.vm.ToValue(utils.StopMining(self.ethereum)) + return v +} + +func (self *JSRE) startMining(call otto.FunctionCall) otto.Value { + v, _ := self.vm.ToValue(utils.StartMining(self.ethereum)) + return v +} + // eth.watch -func (self JSRE) watch(call otto.FunctionCall) otto.Value { +func (self *JSRE) watch(call otto.FunctionCall) otto.Value { addr, _ := call.Argument(0).ToString() var storageAddr string var cb otto.Value -- cgit v1.2.3 From 5f8911f7cba2cf837d891735f46b02b34e4fc228 Mon Sep 17 00:00:00 2001 From: obscuren Date: Thu, 22 May 2014 10:38:37 +0200 Subject: Custom identifier --- ethereum/config.go | 2 ++ ethereum/ethereum.go | 7 +++++-- 2 files changed, 7 insertions(+), 2 deletions(-) (limited to 'ethereum') diff --git a/ethereum/config.go b/ethereum/config.go index f25f2fb66..f39f3b7da 100644 --- a/ethereum/config.go +++ b/ethereum/config.go @@ -6,6 +6,7 @@ import ( "os" ) +var Identifier string var StartMining bool var StartRpc bool var RpcPort int @@ -30,6 +31,7 @@ func Init() { flag.PrintDefaults() } + flag.StringVar(&Identifier, "i", "", "Custom client identifier") flag.BoolVar(&StartMining, "m", false, "start dagger mining") flag.BoolVar(&ShowGenesis, "g", false, "prints genesis header and exits") flag.BoolVar(&StartRpc, "r", false, "start rpc server") diff --git a/ethereum/ethereum.go b/ethereum/ethereum.go index 2fdfd5caf..34bacb7b9 100644 --- a/ethereum/ethereum.go +++ b/ethereum/ethereum.go @@ -52,12 +52,15 @@ func main() { var logSys *log.Logger flags := log.LstdFlags + var lt ethutil.LoggerType if StartJsConsole || len(InputFile) > 0 { - ethutil.ReadConfig(DataDir, ethutil.LogFile) + lt = ethutil.LogFile } else { - ethutil.ReadConfig(DataDir, ethutil.LogFile|ethutil.LogStd) + lt = ethutil.LogFile | ethutil.LogStd } + ethutil.ReadConfig(DataDir, lt, Identifier) + logger := ethutil.Config.Log if LogFile != "" { -- cgit v1.2.3 From d35380c19e5ce92b57158e7780f7105dc4136916 Mon Sep 17 00:00:00 2001 From: obscuren Date: Fri, 23 May 2014 14:37:03 +0200 Subject: New main script through init return value --- ethereum/config.go | 3 +-- ethereum/repl.go | 15 ++++++++++++--- ethereum/repl_darwin.go | 2 +- 3 files changed, 14 insertions(+), 6 deletions(-) (limited to 'ethereum') diff --git a/ethereum/config.go b/ethereum/config.go index f39f3b7da..5da910f2b 100644 --- a/ethereum/config.go +++ b/ethereum/config.go @@ -31,7 +31,7 @@ func Init() { flag.PrintDefaults() } - flag.StringVar(&Identifier, "i", "", "Custom client identifier") + flag.StringVar(&Identifier, "i", "", "custom client identifier") flag.BoolVar(&StartMining, "m", false, "start dagger mining") flag.BoolVar(&ShowGenesis, "g", false, "prints genesis header and exits") flag.BoolVar(&StartRpc, "r", false, "start rpc server") @@ -47,7 +47,6 @@ func Init() { flag.StringVar(&ImportKey, "import", "", "imports the given private key (hex)") flag.IntVar(&MaxPeer, "x", 10, "maximum desired peers") flag.BoolVar(&StartJsConsole, "js", false, "exp") - //flag.StringVar(&InputFile, "e", "", "Run javascript file") flag.Parse() diff --git a/ethereum/repl.go b/ethereum/repl.go index d1243d19c..10f51675e 100644 --- a/ethereum/repl.go +++ b/ethereum/repl.go @@ -48,13 +48,22 @@ func (self *JSRepl) parseInput(code string) { // The JSEthereum object attempts to wrap the PEthereum object and returns // meaningful javascript objects +type JSBlock struct { + *ethpub.PBlock + eth *JSEthereum +} + +func (self *JSBlock) GetTransaction(hash string) otto.Value { + return self.eth.toVal(self.PBlock.GetTransaction(hash)) +} + type JSEthereum struct { *ethpub.PEthereum vm *otto.Otto } func (self *JSEthereum) GetBlock(hash string) otto.Value { - return self.toVal(self.PEthereum.GetBlock(hash)) + return self.toVal(&JSBlock{self.PEthereum.GetBlock(hash), self}) } func (self *JSEthereum) GetKey() otto.Value { @@ -76,8 +85,8 @@ func (self *JSEthereum) Transact(key, recipient, valueStr, gasStr, gasPriceStr, return self.toVal(r) } -func (self *JSEthereum) Create(key, valueStr, gasStr, gasPriceStr, initStr, bodyStr string) otto.Value { - r, err := self.PEthereum.Create(key, valueStr, gasStr, gasPriceStr, initStr, bodyStr) +func (self *JSEthereum) Create(key, valueStr, gasStr, gasPriceStr, scriptStr string) otto.Value { + r, err := self.PEthereum.Create(key, valueStr, gasStr, gasPriceStr, scriptStr) if err != nil { fmt.Println(err) diff --git a/ethereum/repl_darwin.go b/ethereum/repl_darwin.go index fa36b0d52..b61d4edd7 100644 --- a/ethereum/repl_darwin.go +++ b/ethereum/repl_darwin.go @@ -102,7 +102,7 @@ L: break L } - addHistory(str) //allow user to recall this line + addHistory(str[:len(str)-1]) //allow user to recall this line self.parseInput(str) -- cgit v1.2.3 From 65c5a20e1c04c996f96f81cd959ab986b8482b6a Mon Sep 17 00:00:00 2001 From: obscuren Date: Fri, 30 May 2014 16:56:56 +0200 Subject: Added config file setup. Fixes #59 * Also fixes asset path problems --- ethereum/config.go | 18 ++++++++---------- ethereum/ethereum.go | 2 +- 2 files changed, 9 insertions(+), 11 deletions(-) (limited to 'ethereum') diff --git a/ethereum/config.go b/ethereum/config.go index 5da910f2b..39dc11727 100644 --- a/ethereum/config.go +++ b/ethereum/config.go @@ -20,7 +20,6 @@ var UseSeed bool var ImportKey string var ExportKey bool var LogFile string -var DataDir string var NonInteractive bool var StartJsConsole bool var InputFile string @@ -31,22 +30,21 @@ func Init() { flag.PrintDefaults() } - flag.StringVar(&Identifier, "i", "", "custom client identifier") - flag.BoolVar(&StartMining, "m", false, "start dagger mining") - flag.BoolVar(&ShowGenesis, "g", false, "prints genesis header and exits") - flag.BoolVar(&StartRpc, "r", false, "start rpc server") + flag.StringVar(&Identifier, "id", "", "Custom client identifier") + flag.StringVar(&OutboundPort, "port", "30303", "listening port") + flag.BoolVar(&UseUPnP, "upnp", false, "enable UPnP support") + flag.IntVar(&MaxPeer, "maxpeer", 10, "maximum desired peers") flag.IntVar(&RpcPort, "rpcport", 8080, "port to start json-rpc server on") + flag.BoolVar(&StartRpc, "rpc", false, "start rpc server") + flag.BoolVar(&StartJsConsole, "js", false, "exp") + + flag.BoolVar(&StartMining, "mine", false, "start dagger mining") flag.BoolVar(&NonInteractive, "y", false, "non-interactive mode (say yes to confirmations)") - flag.BoolVar(&UseUPnP, "upnp", false, "enable UPnP support") flag.BoolVar(&UseSeed, "seed", true, "seed peers") flag.BoolVar(&GenAddr, "genaddr", false, "create a new priv/pub key") flag.BoolVar(&ExportKey, "export", false, "export private key") - flag.StringVar(&OutboundPort, "p", "30303", "listening port") flag.StringVar(&LogFile, "logfile", "", "log file (defaults to standard output)") - flag.StringVar(&DataDir, "dir", ".ethereum", "ethereum data directory") flag.StringVar(&ImportKey, "import", "", "imports the given private key (hex)") - flag.IntVar(&MaxPeer, "x", 10, "maximum desired peers") - flag.BoolVar(&StartJsConsole, "js", false, "exp") flag.Parse() diff --git a/ethereum/ethereum.go b/ethereum/ethereum.go index 34bacb7b9..7bb668235 100644 --- a/ethereum/ethereum.go +++ b/ethereum/ethereum.go @@ -59,7 +59,7 @@ func main() { lt = ethutil.LogFile | ethutil.LogStd } - ethutil.ReadConfig(DataDir, lt, Identifier) + ethutil.ReadConfig(".ethereum", lt, Identifier) logger := ethutil.Config.Log -- cgit v1.2.3 From 0bdb0a9d58be08e210eb94dc6893f6103202ae7c Mon Sep 17 00:00:00 2001 From: obscuren Date: Fri, 30 May 2014 19:36:05 +0200 Subject: Added ini file for ethereum. fixes #66 --- ethereum/ethereum.go | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) (limited to 'ethereum') diff --git a/ethereum/ethereum.go b/ethereum/ethereum.go index 7bb668235..ecbf04c9a 100644 --- a/ethereum/ethereum.go +++ b/ethereum/ethereum.go @@ -6,10 +6,12 @@ import ( "github.com/ethereum/eth-go/ethchain" "github.com/ethereum/eth-go/ethutil" "github.com/ethereum/go-ethereum/utils" + "github.com/rakyll/globalconf" "io/ioutil" "log" "os" "os/signal" + "path" "runtime" "strings" ) @@ -59,7 +61,15 @@ func main() { lt = ethutil.LogFile | ethutil.LogStd } - ethutil.ReadConfig(".ethereum", lt, Identifier) + g, err := globalconf.NewWithOptions(&globalconf.Options{ + Filename: path.Join(ethutil.ApplicationFolder(".ethereal"), "conf.ini"), + }) + if err != nil { + fmt.Println(err) + } else { + g.ParseAll() + } + ethutil.ReadConfig(".ethereum", lt, g, Identifier) logger := ethutil.Config.Log -- cgit v1.2.3 From 98811f11e5d7ccf6e053b46b9ca2ed897140ce47 Mon Sep 17 00:00:00 2001 From: obscuren Date: Sat, 31 May 2014 11:43:08 +0200 Subject: ethereum instead of ethereal. Fixes #69 --- ethereum/ethereum.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'ethereum') diff --git a/ethereum/ethereum.go b/ethereum/ethereum.go index ecbf04c9a..56ea46122 100644 --- a/ethereum/ethereum.go +++ b/ethereum/ethereum.go @@ -62,7 +62,7 @@ func main() { } g, err := globalconf.NewWithOptions(&globalconf.Options{ - Filename: path.Join(ethutil.ApplicationFolder(".ethereal"), "conf.ini"), + Filename: path.Join(ethutil.ApplicationFolder(".ethereum"), "conf.ini"), }) if err != nil { fmt.Println(err) -- cgit v1.2.3 From a6f4eef1dadee9d8caa9b0ac20e2ce4a3034a100 Mon Sep 17 00:00:00 2001 From: Maran Date: Mon, 2 Jun 2014 15:16:37 +0200 Subject: Added Peer Window --- ethereum/repl.go | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'ethereum') diff --git a/ethereum/repl.go b/ethereum/repl.go index 10f51675e..e59814154 100644 --- a/ethereum/repl.go +++ b/ethereum/repl.go @@ -66,6 +66,10 @@ func (self *JSEthereum) GetBlock(hash string) otto.Value { return self.toVal(&JSBlock{self.PEthereum.GetBlock(hash), self}) } +func (self *JSEthereum) GetPeers() otto.Value { + return self.toVal(self.PEthereum.GetPeers()) +} + func (self *JSEthereum) GetKey() otto.Value { return self.toVal(self.PEthereum.GetKey()) } -- cgit v1.2.3 From 307fe4a3cd4ff2d3910ed992e6e98a7cd3ca6f87 Mon Sep 17 00:00:00 2001 From: Maran Date: Wed, 4 Jun 2014 12:19:50 +0200 Subject: Add loading of extra build in js files to JS-Repl. Implements #67 --- ethereum/javascript_runtime.go | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) (limited to 'ethereum') diff --git a/ethereum/javascript_runtime.go b/ethereum/javascript_runtime.go index 93297f604..b05d39232 100644 --- a/ethereum/javascript_runtime.go +++ b/ethereum/javascript_runtime.go @@ -10,6 +10,7 @@ import ( "github.com/obscuren/otto" "io/ioutil" "os" + "path" "path/filepath" ) @@ -25,6 +26,20 @@ type JSRE struct { objectCb map[string][]otto.Value } +func (jsre *JSRE) LoadExtFile(path string) { + result, err := ioutil.ReadFile(path) + if err == nil { + jsre.vm.Run(result) + } else { + ethutil.Config.Log.Debugln("Could not load file:", path) + } +} + +func (jsre *JSRE) LoadIntFile(file string) { + assetPath := path.Join(os.Getenv("GOPATH"), "src", "github.com", "ethereum", "go-ethereum", "ethereal", "assets", "ext") + jsre.LoadExtFile(path.Join(assetPath, file)) +} + func NewJSRE(ethereum *eth.Ethereum) *JSRE { re := &JSRE{ ethereum, @@ -39,6 +54,10 @@ func NewJSRE(ethereum *eth.Ethereum) *JSRE { // Init the JS lib re.vm.Run(jsLib) + // Load extra javascript files + re.LoadIntFile("string.js") + re.LoadIntFile("big.js") + // We have to make sure that, whoever calls this, calls "Stop" go re.mainLoop() -- cgit v1.2.3 From 7843390ecd52df37a28282d76be198d5456ce385 Mon Sep 17 00:00:00 2001 From: Maran Date: Wed, 4 Jun 2014 15:54:33 +0200 Subject: Implement getStateKeyVal for JS bindings. Gives JS the option to 'loop' over contract key/val storage --- ethereum/repl.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'ethereum') diff --git a/ethereum/repl.go b/ethereum/repl.go index e59814154..0208459ad 100644 --- a/ethereum/repl.go +++ b/ethereum/repl.go @@ -78,6 +78,10 @@ func (self *JSEthereum) GetStateObject(addr string) otto.Value { return self.toVal(self.PEthereum.GetStateObject(addr)) } +func (self *JSEthereum) GetStateKeyVals(addr string) otto.Value { + return self.toVal(self.PEthereum.GetStateObject(addr).StateKeyVal(false)) +} + func (self *JSEthereum) Transact(key, recipient, valueStr, gasStr, gasPriceStr, dataStr string) otto.Value { r, err := self.PEthereum.Transact(key, recipient, valueStr, gasStr, gasPriceStr, dataStr) if err != nil { @@ -105,7 +109,7 @@ func (self *JSEthereum) toVal(v interface{}) otto.Value { result, err := self.vm.ToValue(v) if err != nil { - fmt.Println(err) + fmt.Println("Value unknown:", err) return otto.UndefinedValue() } -- cgit v1.2.3 From e36badd744bc79c652deb3d45da1438982ec622a Mon Sep 17 00:00:00 2001 From: Maran Date: Wed, 11 Jun 2014 12:33:11 +0200 Subject: Reimplement -datadir flag. Implements #79 The config file is actually loaded from the folder that datadir points at --- ethereum/config.go | 4 ++++ ethereum/ethereum.go | 4 ++-- 2 files changed, 6 insertions(+), 2 deletions(-) (limited to 'ethereum') diff --git a/ethereum/config.go b/ethereum/config.go index 39dc11727..a80b47a8e 100644 --- a/ethereum/config.go +++ b/ethereum/config.go @@ -24,6 +24,8 @@ var NonInteractive bool var StartJsConsole bool var InputFile string +var Datadir string + func Init() { flag.Usage = func() { fmt.Fprintf(os.Stderr, "%s [options] [filename]:\n", os.Args[0]) @@ -46,6 +48,8 @@ func Init() { flag.StringVar(&LogFile, "logfile", "", "log file (defaults to standard output)") flag.StringVar(&ImportKey, "import", "", "imports the given private key (hex)") + flag.StringVar(&Datadir, "datadir", ".ethereum", "specifies the datadir to use. Takes precedence over config file.") + flag.Parse() InputFile = flag.Arg(0) diff --git a/ethereum/ethereum.go b/ethereum/ethereum.go index 56ea46122..179a3f462 100644 --- a/ethereum/ethereum.go +++ b/ethereum/ethereum.go @@ -62,14 +62,14 @@ func main() { } g, err := globalconf.NewWithOptions(&globalconf.Options{ - Filename: path.Join(ethutil.ApplicationFolder(".ethereum"), "conf.ini"), + Filename: path.Join(ethutil.ApplicationFolder(Datadir), "conf.ini"), }) if err != nil { fmt.Println(err) } else { g.ParseAll() } - ethutil.ReadConfig(".ethereum", lt, g, Identifier) + ethutil.ReadConfig(Datadir, lt, g, Identifier) logger := ethutil.Config.Log -- cgit v1.2.3 From 3744151359a7ff352fde5be39905ecb3d22c9d28 Mon Sep 17 00:00:00 2001 From: obscuren Date: Mon, 16 Jun 2014 11:15:08 +0200 Subject: Removed init fees --- ethereum/ethereum.go | 3 --- 1 file changed, 3 deletions(-) (limited to 'ethereum') diff --git a/ethereum/ethereum.go b/ethereum/ethereum.go index 179a3f462..8812e0a60 100644 --- a/ethereum/ethereum.go +++ b/ethereum/ethereum.go @@ -3,7 +3,6 @@ package main import ( "fmt" "github.com/ethereum/eth-go" - "github.com/ethereum/eth-go/ethchain" "github.com/ethereum/eth-go/ethutil" "github.com/ethereum/go-ethereum/utils" "github.com/rakyll/globalconf" @@ -86,8 +85,6 @@ func main() { logSys = log.New(os.Stdout, "", flags) } - ethchain.InitFees() - // Instantiated a eth stack ethereum, err := eth.New(eth.CapDefault, UseUPnP) if err != nil { -- 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 --- ethereum/javascript_runtime.go | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) (limited to 'ethereum') diff --git a/ethereum/javascript_runtime.go b/ethereum/javascript_runtime.go index b05d39232..737f7663f 100644 --- a/ethereum/javascript_runtime.go +++ b/ethereum/javascript_runtime.go @@ -138,6 +138,7 @@ func (self *JSRE) initStdFuncs() { eth.Set("require", self.require) eth.Set("stopMining", self.stopMining) eth.Set("startMining", self.startMining) + eth.Set("blockDo", self.execBlock) } /* @@ -207,3 +208,18 @@ func (self *JSRE) require(call otto.FunctionCall) otto.Value { return t } + +func (self *JSRE) execBlock(call otto.FunctionCall) otto.Value { + hash, err := call.Argument(0).ToString() + if err != nil { + return otto.UndefinedValue() + } + + err = self.ethereum.BlockDo(ethutil.FromHex(hash)) + if err != nil { + fmt.Println(err) + return otto.FalseValue() + } + + return otto.TrueValue() +} -- cgit v1.2.3 From f90001e938ce34457cc0ed5822c8e7dff52ec58c Mon Sep 17 00:00:00 2001 From: zelig Date: Mon, 23 Jun 2014 11:38:14 +0100 Subject: add logging start/exit to js console --- ethereum/repl.go | 2 ++ 1 file changed, 2 insertions(+) (limited to 'ethereum') diff --git a/ethereum/repl.go b/ethereum/repl.go index 0208459ad..a95d73300 100644 --- a/ethereum/repl.go +++ b/ethereum/repl.go @@ -23,11 +23,13 @@ func NewJSRepl(ethereum *eth.Ethereum) *JSRepl { } func (self *JSRepl) Start() { + logger.Infoln("init JS Console") self.read() } func (self *JSRepl) Stop() { self.re.Stop() + logger.Infoln("exit JS Console") } func (self *JSRepl) parseInput(code string) { -- cgit v1.2.3 From 7bcf875c577cd9710d27dd4511ae21aa62067d79 Mon Sep 17 00:00:00 2001 From: zelig Date: Mon, 23 Jun 2014 11:39:09 +0100 Subject: add logging for jsre --- ethereum/javascript_runtime.go | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) (limited to 'ethereum') diff --git a/ethereum/javascript_runtime.go b/ethereum/javascript_runtime.go index b05d39232..34b805e7f 100644 --- a/ethereum/javascript_runtime.go +++ b/ethereum/javascript_runtime.go @@ -6,6 +6,7 @@ import ( "github.com/ethereum/eth-go/ethchain" "github.com/ethereum/eth-go/ethpub" "github.com/ethereum/eth-go/ethutil" + "github.com/ethereum/eth-go/ethlog" "github.com/ethereum/go-ethereum/utils" "github.com/obscuren/otto" "io/ioutil" @@ -14,6 +15,8 @@ import ( "path/filepath" ) +var jsrelogger = ethlog.NewLogger("JSRE") + type JSRE struct { ethereum *eth.Ethereum vm *otto.Otto @@ -31,7 +34,7 @@ func (jsre *JSRE) LoadExtFile(path string) { if err == nil { jsre.vm.Run(result) } else { - ethutil.Config.Log.Debugln("Could not load file:", path) + jsrelogger.Debugln("Could not load file:", path) } } @@ -65,6 +68,8 @@ func NewJSRE(ethereum *eth.Ethereum) *JSRE { re.initStdFuncs() + jsrelogger.Infoln("started") + return re } @@ -99,6 +104,7 @@ func (self *JSRE) Stop() { close(self.blockChan) close(self.quitChan) close(self.changeChan) + jsrelogger.Infoln("stopped") } func (self *JSRE) mainLoop() { -- 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 --- ethereum/cmd.go | 33 +++++++++ ethereum/config.go | 56 --------------- ethereum/ethereum.go | 193 --------------------------------------------------- ethereum/flags.go | 72 +++++++++++++++++++ ethereum/main.go | 47 +++++++++++++ 5 files changed, 152 insertions(+), 249 deletions(-) create mode 100644 ethereum/cmd.go delete mode 100644 ethereum/config.go delete mode 100644 ethereum/ethereum.go create mode 100644 ethereum/flags.go create mode 100644 ethereum/main.go (limited to 'ethereum') diff --git a/ethereum/cmd.go b/ethereum/cmd.go new file mode 100644 index 000000000..0e9c2be8c --- /dev/null +++ b/ethereum/cmd.go @@ -0,0 +1,33 @@ +package main + +import ( + "github.com/ethereum/eth-go" + "github.com/ethereum/go-ethereum/utils" + "os" + "io/ioutil" +) + +func InitJsConsole(ethereum *eth.Ethereum) { + repl := NewJSRepl(ethereum) + go repl.Start() + utils.RegisterInterrupt(func(os.Signal) { + repl.Stop() + ethereum.Stop() + }) +} + +func ExecJsFile (ethereum *eth.Ethereum, InputFile string) { + file, err := os.Open(InputFile) + if err != nil { + logger.Fatalln(err) + } + content, err := ioutil.ReadAll(file) + if err != nil { + logger.Fatalln(err) + } + re := NewJSRE(ethereum) + utils.RegisterInterrupt(func(os.Signal) { + re.Stop() + }) + re.Run(string(content)) +} diff --git a/ethereum/config.go b/ethereum/config.go deleted file mode 100644 index a80b47a8e..000000000 --- a/ethereum/config.go +++ /dev/null @@ -1,56 +0,0 @@ -package main - -import ( - "flag" - "fmt" - "os" -) - -var Identifier string -var StartMining bool -var StartRpc bool -var RpcPort int -var UseUPnP bool -var OutboundPort string -var ShowGenesis bool -var AddPeer string -var MaxPeer int -var GenAddr bool -var UseSeed bool -var ImportKey string -var ExportKey bool -var LogFile string -var NonInteractive bool -var StartJsConsole bool -var InputFile string - -var Datadir string - -func Init() { - flag.Usage = func() { - fmt.Fprintf(os.Stderr, "%s [options] [filename]:\n", os.Args[0]) - flag.PrintDefaults() - } - - flag.StringVar(&Identifier, "id", "", "Custom client identifier") - flag.StringVar(&OutboundPort, "port", "30303", "listening port") - flag.BoolVar(&UseUPnP, "upnp", false, "enable UPnP support") - flag.IntVar(&MaxPeer, "maxpeer", 10, "maximum desired peers") - flag.IntVar(&RpcPort, "rpcport", 8080, "port to start json-rpc server on") - flag.BoolVar(&StartRpc, "rpc", false, "start rpc server") - flag.BoolVar(&StartJsConsole, "js", false, "exp") - - flag.BoolVar(&StartMining, "mine", false, "start dagger mining") - flag.BoolVar(&NonInteractive, "y", false, "non-interactive mode (say yes to confirmations)") - flag.BoolVar(&UseSeed, "seed", true, "seed peers") - flag.BoolVar(&GenAddr, "genaddr", false, "create a new priv/pub key") - flag.BoolVar(&ExportKey, "export", false, "export private key") - flag.StringVar(&LogFile, "logfile", "", "log file (defaults to standard output)") - flag.StringVar(&ImportKey, "import", "", "imports the given private key (hex)") - - flag.StringVar(&Datadir, "datadir", ".ethereum", "specifies the datadir to use. Takes precedence over config file.") - - flag.Parse() - - InputFile = flag.Arg(0) -} diff --git a/ethereum/ethereum.go b/ethereum/ethereum.go deleted file mode 100644 index 8812e0a60..000000000 --- a/ethereum/ethereum.go +++ /dev/null @@ -1,193 +0,0 @@ -package main - -import ( - "fmt" - "github.com/ethereum/eth-go" - "github.com/ethereum/eth-go/ethutil" - "github.com/ethereum/go-ethereum/utils" - "github.com/rakyll/globalconf" - "io/ioutil" - "log" - "os" - "os/signal" - "path" - "runtime" - "strings" -) - -const Debug = true - -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) - } - }() -} - -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 main() { - Init() - - runtime.GOMAXPROCS(runtime.NumCPU()) - - // set logger - var logSys *log.Logger - flags := log.LstdFlags - - var lt ethutil.LoggerType - if StartJsConsole || len(InputFile) > 0 { - lt = ethutil.LogFile - } else { - lt = ethutil.LogFile | ethutil.LogStd - } - - g, err := globalconf.NewWithOptions(&globalconf.Options{ - Filename: path.Join(ethutil.ApplicationFolder(Datadir), "conf.ini"), - }) - if err != nil { - fmt.Println(err) - } else { - g.ParseAll() - } - ethutil.ReadConfig(Datadir, lt, g, Identifier) - - logger := ethutil.Config.Log - - if LogFile != "" { - logfile, err := os.OpenFile(LogFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) - if err != nil { - panic(fmt.Sprintf("error opening log file '%s': %v", LogFile, err)) - } - defer logfile.Close() - log.SetOutput(logfile) - logSys = log.New(logfile, "", flags) - logger.AddLogSystem(logSys) - } else { - logSys = log.New(os.Stdout, "", flags) - } - - // Instantiated a eth stack - ethereum, err := eth.New(eth.CapDefault, UseUPnP) - if err != nil { - log.Println("eth start err:", err) - return - } - ethereum.Port = OutboundPort - - // bookkeeping tasks - switch { - case GenAddr: - if NonInteractive || confirm("This action overwrites your old private key.") { - utils.CreateKeyPair(true) - } - os.Exit(0) - case len(ImportKey) > 0: - if NonInteractive || confirm("This action overwrites your old private key.") { - mnemonic := strings.Split(ImportKey, " ") - if len(mnemonic) == 24 { - logSys.Println("Got mnemonic key, importing.") - key := ethutil.MnemonicDecode(mnemonic) - utils.ImportPrivateKey(key) - } else if len(mnemonic) == 1 { - logSys.Println("Got hex key, importing.") - utils.ImportPrivateKey(ImportKey) - } else { - logSys.Println("Did not recognise format, exiting.") - } - } - os.Exit(0) - case ExportKey: - 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) - - os.Exit(0) - case ShowGenesis: - logSys.Println(ethereum.BlockChain().Genesis()) - os.Exit(0) - default: - // Creates a keypair if non exists - utils.CreateKeyPair(false) - } - - // client - logger.Infoln(fmt.Sprintf("Starting Ethereum v%s", ethutil.Config.Ver)) - - // Set the max peers - ethereum.MaxPeers = MaxPeer - - // Set Mining status - ethereum.Mining = StartMining - - if StartMining { - utils.DoMining(ethereum) - } - - if StartJsConsole { - repl := NewJSRepl(ethereum) - - go repl.Start() - - RegisterInterrupt(func(os.Signal) { - repl.Stop() - }) - } else if len(InputFile) > 0 { - file, err := os.Open(InputFile) - if err != nil { - ethutil.Config.Log.Fatal(err) - } - - content, err := ioutil.ReadAll(file) - if err != nil { - ethutil.Config.Log.Fatal(err) - } - - re := NewJSRE(ethereum) - RegisterInterrupt(func(os.Signal) { - re.Stop() - }) - re.Run(string(content)) - } - - if StartRpc { - utils.DoRpc(ethereum, RpcPort) - } - - RegisterInterrupt(func(sig os.Signal) { - fmt.Printf("Shutting down (%v) ... \n", sig) - ethereum.Stop() - }) - - ethereum.Start(UseSeed) - - // Wait for shutdown - ethereum.WaitForShutdown() -} diff --git a/ethereum/flags.go b/ethereum/flags.go new file mode 100644 index 000000000..513d93a6d --- /dev/null +++ b/ethereum/flags.go @@ -0,0 +1,72 @@ +package main + +import ( + "flag" + "fmt" + "os" + "os/user" + "path" + "github.com/ethereum/eth-go/ethlog" +) + +var Identifier string +var StartRpc bool +var RpcPort int +var UseUPnP bool +var OutboundPort string +var ShowGenesis bool +var AddPeer string +var MaxPeer int +var GenAddr bool +var UseSeed bool +var ImportKey string +var ExportKey bool +var NonInteractive bool +var Datadir string +var LogFile string +var ConfigFile string +var DebugFile string +var LogLevel int + +// flags specific to cli client +var StartMining bool +var StartJsConsole bool +var InputFile string + +func defaultDataDir() string { + usr, _ := user.Current() + return path.Join(usr.HomeDir, ".ethereum") +} + +var defaultConfigFile = path.Join(defaultDataDir(), "conf.ini") + +func Init() { + flag.Usage = func() { + fmt.Fprintf(os.Stderr, "%s [options] [filename]:\noptions precedence: default < config file < environment variables < command line", os.Args[0]) + flag.PrintDefaults() + } + + flag.StringVar(&Identifier, "id", "", "Custom client identifier") + flag.StringVar(&OutboundPort, "port", "30303", "listening port") + flag.BoolVar(&UseUPnP, "upnp", false, "enable UPnP support") + flag.IntVar(&MaxPeer, "maxpeer", 10, "maximum desired peers") + flag.IntVar(&RpcPort, "rpcport", 8080, "port to start json-rpc server on") + flag.BoolVar(&StartRpc, "rpc", false, "start rpc server") + flag.BoolVar(&NonInteractive, "y", false, "non-interactive mode (say yes to confirmations)") + flag.BoolVar(&UseSeed, "seed", true, "seed peers") + flag.BoolVar(&GenAddr, "genaddr", false, "create a new priv/pub key") + flag.BoolVar(&ExportKey, "export", false, "export private key") + flag.StringVar(&LogFile, "logfile", "", "log file (defaults to standard output)") + flag.StringVar(&ImportKey, "import", "", "imports the given private key (hex)") + flag.StringVar(&Datadir, "datadir", defaultDataDir(), "specifies the datadir to use") + flag.StringVar(&ConfigFile, "conf", defaultConfigFile, "config file") + flag.StringVar(&DebugFile, "debug", "", "debug file (no debugging if not set)") + flag.IntVar(&LogLevel, "loglevel", int(ethlog.InfoLevel), "loglevel: 0-4: silent,error,warn,info,debug)") + + flag.BoolVar(&StartMining, "mine", false, "start dagger mining") + flag.BoolVar(&StartJsConsole, "js", false, "launches javascript console") + + flag.Parse() + + InputFile = flag.Arg(0) +} diff --git a/ethereum/main.go b/ethereum/main.go new file mode 100644 index 000000000..bbbaf5541 --- /dev/null +++ b/ethereum/main.go @@ -0,0 +1,47 @@ +package main + +import ( + "github.com/ethereum/go-ethereum/utils" + "github.com/ethereum/eth-go/ethlog" + "runtime" +) + +var logger = ethlog.NewLogger("CLI") + +func main() { + runtime.GOMAXPROCS(runtime.NumCPU()) + + // precedence: code-internal flag default < config file < environment variables < command line + Init() // parsing command line + utils.InitConfig(ConfigFile, Datadir, Identifier, "ETH") + + utils.InitDataDir(Datadir) + + utils.InitLogging(Datadir, LogFile, LogLevel, DebugFile) + + ethereum := utils.NewEthereum(UseUPnP, OutboundPort, MaxPeer) + + // create, import, export keys + utils.KeyTasks(GenAddr, ImportKey, ExportKey, NonInteractive) + + if ShowGenesis { + utils.ShowGenesis(ethereum) + } + + if StartMining { + utils.StartMining(ethereum) + } + + // better reworked as cases + if StartJsConsole { + InitJsConsole(ethereum) + } else if len(InputFile) > 0 { + ExecJsFile(ethereum, InputFile) + } + + if StartRpc { + utils.StartRpc(ethereum, RpcPort) + } + + utils.StartEthereum(ethereum, UseSeed) +} -- cgit v1.2.3 From 17e8d7519b1aac322db08b857e63db82a322d6cf Mon Sep 17 00:00:00 2001 From: obscuren Date: Tue, 24 Jun 2014 09:36:05 +0200 Subject: Renamed execBlock --- ethereum/javascript_runtime.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'ethereum') diff --git a/ethereum/javascript_runtime.go b/ethereum/javascript_runtime.go index 737f7663f..92d9c119f 100644 --- a/ethereum/javascript_runtime.go +++ b/ethereum/javascript_runtime.go @@ -138,7 +138,7 @@ func (self *JSRE) initStdFuncs() { eth.Set("require", self.require) eth.Set("stopMining", self.stopMining) eth.Set("startMining", self.startMining) - eth.Set("blockDo", self.execBlock) + eth.Set("execBlock", self.execBlock) } /* -- cgit v1.2.3 From fd1ddbce6892e3f0e09eec68687b6ef34b216888 Mon Sep 17 00:00:00 2001 From: obscuren Date: Tue, 24 Jun 2014 10:09:02 +0200 Subject: Save repl history to file and recall on next session --- ethereum/repl.go | 27 ++++++++++++++++++++++++++- ethereum/repl_darwin.go | 4 +++- 2 files changed, 29 insertions(+), 2 deletions(-) (limited to 'ethereum') diff --git a/ethereum/repl.go b/ethereum/repl.go index 0208459ad..dd8d08179 100644 --- a/ethereum/repl.go +++ b/ethereum/repl.go @@ -1,10 +1,15 @@ package main import ( + "bufio" "fmt" "github.com/ethereum/eth-go" "github.com/ethereum/eth-go/ethpub" + "github.com/ethereum/eth-go/ethutil" "github.com/obscuren/otto" + "io" + "os" + "path" ) type Repl interface { @@ -16,18 +21,38 @@ type JSRepl struct { re *JSRE prompt string + + history *os.File } func NewJSRepl(ethereum *eth.Ethereum) *JSRepl { - return &JSRepl{re: NewJSRE(ethereum), prompt: "> "} + hist, err := os.OpenFile(path.Join(ethutil.Config.ExecPath, "history"), os.O_RDWR|os.O_CREATE, os.ModePerm) + if err != nil { + panic(err) + } + + return &JSRepl{re: NewJSRE(ethereum), prompt: "> ", history: hist} } func (self *JSRepl) Start() { + reader := bufio.NewReader(self.history) + for { + line, err := reader.ReadString('\n') + if err != nil && err == io.EOF { + break + } else if err != nil { + fmt.Println("error reading history", err) + break + } + + addHistory(line[:len(line)-1]) + } self.read() } func (self *JSRepl) Stop() { self.re.Stop() + self.history.Close() } func (self *JSRepl) parseInput(code string) { diff --git a/ethereum/repl_darwin.go b/ethereum/repl_darwin.go index b61d4edd7..62b40059a 100644 --- a/ethereum/repl_darwin.go +++ b/ethereum/repl_darwin.go @@ -102,7 +102,9 @@ L: break L } - addHistory(str[:len(str)-1]) //allow user to recall this line + hist := str[:len(str)-1] + addHistory(hist) //allow user to recall this line + self.history.WriteString(str) self.parseInput(str) -- 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 --- ethereum/javascript_runtime.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'ethereum') diff --git a/ethereum/javascript_runtime.go b/ethereum/javascript_runtime.go index 92d9c119f..a9b12629a 100644 --- a/ethereum/javascript_runtime.go +++ b/ethereum/javascript_runtime.go @@ -215,7 +215,7 @@ func (self *JSRE) execBlock(call otto.FunctionCall) otto.Value { return otto.UndefinedValue() } - err = self.ethereum.BlockDo(ethutil.FromHex(hash)) + err = utils.BlockDo(self.ethereum, ethutil.FromHex(hash)) if err != nil { fmt.Println(err) return otto.FalseValue() -- cgit v1.2.3 From 8ee1abecb971e39ad5e0ed5b199ff4bf553ca67a Mon Sep 17 00:00:00 2001 From: zelig Date: Wed, 25 Jun 2014 16:54:29 +0100 Subject: update log levels to include DebugDetail; correct default datadir for ethereal --- ethereum/flags.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'ethereum') diff --git a/ethereum/flags.go b/ethereum/flags.go index 513d93a6d..99aa9b250 100644 --- a/ethereum/flags.go +++ b/ethereum/flags.go @@ -61,7 +61,7 @@ func Init() { flag.StringVar(&Datadir, "datadir", defaultDataDir(), "specifies the datadir to use") flag.StringVar(&ConfigFile, "conf", defaultConfigFile, "config file") flag.StringVar(&DebugFile, "debug", "", "debug file (no debugging if not set)") - flag.IntVar(&LogLevel, "loglevel", int(ethlog.InfoLevel), "loglevel: 0-4: silent,error,warn,info,debug)") + flag.IntVar(&LogLevel, "loglevel", int(ethlog.InfoLevel), "loglevel: 0-5: silent,error,warn,info,debug,debug detail)") flag.BoolVar(&StartMining, "mine", false, "start dagger mining") flag.BoolVar(&StartJsConsole, "js", false, "launches javascript console") -- cgit v1.2.3 From bf57e9603b9ef2c96e8e6d7c3d22ea674392d56b Mon Sep 17 00:00:00 2001 From: zelig Date: Wed, 25 Jun 2014 18:09:42 +0100 Subject: add newline to help usage msg --- ethereum/flags.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'ethereum') diff --git a/ethereum/flags.go b/ethereum/flags.go index 99aa9b250..232a2bc92 100644 --- a/ethereum/flags.go +++ b/ethereum/flags.go @@ -42,7 +42,7 @@ var defaultConfigFile = path.Join(defaultDataDir(), "conf.ini") func Init() { flag.Usage = func() { - fmt.Fprintf(os.Stderr, "%s [options] [filename]:\noptions precedence: default < config file < environment variables < command line", os.Args[0]) + fmt.Fprintf(os.Stderr, "%s [options] [filename]:\noptions precedence: default < config file < environment variables < command line\n", os.Args[0]) flag.PrintDefaults() } -- cgit v1.2.3 From 6763d28a170b4e91c78532feed68805fe88c41dd Mon Sep 17 00:00:00 2001 From: zelig Date: Wed, 25 Jun 2014 18:18:22 +0100 Subject: repl.Stop() to only if running, fixes panic after js> exit followed by interrupt --- ethereum/repl.go | 38 +++++++++++++++++++++++--------------- 1 file changed, 23 insertions(+), 15 deletions(-) (limited to 'ethereum') diff --git a/ethereum/repl.go b/ethereum/repl.go index c162c78b0..34380a06f 100644 --- a/ethereum/repl.go +++ b/ethereum/repl.go @@ -23,6 +23,8 @@ type JSRepl struct { prompt string history *os.File + + running bool } func NewJSRepl(ethereum *eth.Ethereum) *JSRepl { @@ -35,26 +37,32 @@ func NewJSRepl(ethereum *eth.Ethereum) *JSRepl { } func (self *JSRepl) Start() { - logger.Infoln("init JS Console") - reader := bufio.NewReader(self.history) - for { - line, err := reader.ReadString('\n') - if err != nil && err == io.EOF { - break - } else if err != nil { - fmt.Println("error reading history", err) - break + if !self.running { + self.running = true + logger.Infoln("init JS Console") + reader := bufio.NewReader(self.history) + for { + line, err := reader.ReadString('\n') + if err != nil && err == io.EOF { + break + } else if err != nil { + fmt.Println("error reading history", err) + break + } + + addHistory(line[:len(line)-1]) } - - addHistory(line[:len(line)-1]) + self.read() } - self.read() } func (self *JSRepl) Stop() { - self.re.Stop() - logger.Infoln("exit JS Console") - self.history.Close() + if self.running { + self.running = false + self.re.Stop() + logger.Infoln("exit JS Console") + self.history.Close() + } } func (self *JSRepl) parseInput(code string) { -- 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 --- ethereum/cmd.go | 1 - ethereum/main.go | 2 ++ 2 files changed, 2 insertions(+), 1 deletion(-) (limited to 'ethereum') diff --git a/ethereum/cmd.go b/ethereum/cmd.go index 0e9c2be8c..2dfd54666 100644 --- a/ethereum/cmd.go +++ b/ethereum/cmd.go @@ -12,7 +12,6 @@ func InitJsConsole(ethereum *eth.Ethereum) { go repl.Start() utils.RegisterInterrupt(func(os.Signal) { repl.Stop() - ethereum.Stop() }) } diff --git a/ethereum/main.go b/ethereum/main.go index bbbaf5541..800486e56 100644 --- a/ethereum/main.go +++ b/ethereum/main.go @@ -11,6 +11,8 @@ var logger = ethlog.NewLogger("CLI") func main() { runtime.GOMAXPROCS(runtime.NumCPU()) + utils.HandleInterrupt() + // precedence: code-internal flag default < config file < environment variables < command line Init() // parsing command line utils.InitConfig(ConfigFile, Datadir, Identifier, "ETH") -- 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 --- ethereum/main.go | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'ethereum') diff --git a/ethereum/main.go b/ethereum/main.go index 800486e56..93b2b47d3 100644 --- a/ethereum/main.go +++ b/ethereum/main.go @@ -46,4 +46,8 @@ func main() { } utils.StartEthereum(ethereum, UseSeed) + + // this blocks the thread + ethereum.WaitForShutdown() + ethlog.Flush() } -- 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 --- ethereum/cmd.go | 46 +++++++++++++++++++++--------------------- ethereum/flags.go | 10 ++++----- ethereum/javascript_runtime.go | 4 ++-- ethereum/main.go | 14 ++++++------- 4 files changed, 37 insertions(+), 37 deletions(-) (limited to 'ethereum') diff --git a/ethereum/cmd.go b/ethereum/cmd.go index 2dfd54666..08147824d 100644 --- a/ethereum/cmd.go +++ b/ethereum/cmd.go @@ -1,32 +1,32 @@ package main import ( - "github.com/ethereum/eth-go" - "github.com/ethereum/go-ethereum/utils" - "os" - "io/ioutil" + "github.com/ethereum/eth-go" + "github.com/ethereum/go-ethereum/utils" + "io/ioutil" + "os" ) func InitJsConsole(ethereum *eth.Ethereum) { - repl := NewJSRepl(ethereum) - go repl.Start() - utils.RegisterInterrupt(func(os.Signal) { - repl.Stop() - }) + repl := NewJSRepl(ethereum) + go repl.Start() + utils.RegisterInterrupt(func(os.Signal) { + repl.Stop() + }) } -func ExecJsFile (ethereum *eth.Ethereum, InputFile string) { - file, err := os.Open(InputFile) - if err != nil { - logger.Fatalln(err) - } - content, err := ioutil.ReadAll(file) - if err != nil { - logger.Fatalln(err) - } - re := NewJSRE(ethereum) - utils.RegisterInterrupt(func(os.Signal) { - re.Stop() - }) - re.Run(string(content)) +func ExecJsFile(ethereum *eth.Ethereum, InputFile string) { + file, err := os.Open(InputFile) + if err != nil { + logger.Fatalln(err) + } + content, err := ioutil.ReadAll(file) + if err != nil { + logger.Fatalln(err) + } + re := NewJSRE(ethereum) + utils.RegisterInterrupt(func(os.Signal) { + re.Stop() + }) + re.Run(string(content)) } diff --git a/ethereum/flags.go b/ethereum/flags.go index 232a2bc92..8fb87cf34 100644 --- a/ethereum/flags.go +++ b/ethereum/flags.go @@ -3,10 +3,10 @@ package main import ( "flag" "fmt" + "github.com/ethereum/eth-go/ethlog" "os" - "os/user" - "path" - "github.com/ethereum/eth-go/ethlog" + "os/user" + "path" ) var Identifier string @@ -34,8 +34,8 @@ var StartJsConsole bool var InputFile string func defaultDataDir() string { - usr, _ := user.Current() - return path.Join(usr.HomeDir, ".ethereum") + usr, _ := user.Current() + return path.Join(usr.HomeDir, ".ethereum") } var defaultConfigFile = path.Join(defaultDataDir(), "conf.ini") diff --git a/ethereum/javascript_runtime.go b/ethereum/javascript_runtime.go index 0a9a882ad..0dfe07a54 100644 --- a/ethereum/javascript_runtime.go +++ b/ethereum/javascript_runtime.go @@ -1,12 +1,12 @@ - package main +package main import ( "fmt" "github.com/ethereum/eth-go" "github.com/ethereum/eth-go/ethchain" + "github.com/ethereum/eth-go/ethlog" "github.com/ethereum/eth-go/ethpub" "github.com/ethereum/eth-go/ethutil" - "github.com/ethereum/eth-go/ethlog" "github.com/ethereum/go-ethereum/utils" "github.com/obscuren/otto" "io/ioutil" diff --git a/ethereum/main.go b/ethereum/main.go index 93b2b47d3..6b1995eec 100644 --- a/ethereum/main.go +++ b/ethereum/main.go @@ -1,8 +1,8 @@ package main import ( - "github.com/ethereum/go-ethereum/utils" "github.com/ethereum/eth-go/ethlog" + "github.com/ethereum/go-ethereum/utils" "runtime" ) @@ -24,11 +24,11 @@ func main() { ethereum := utils.NewEthereum(UseUPnP, OutboundPort, MaxPeer) // create, import, export keys - utils.KeyTasks(GenAddr, ImportKey, ExportKey, NonInteractive) + utils.KeyTasks(GenAddr, ImportKey, ExportKey, NonInteractive) - if ShowGenesis { - utils.ShowGenesis(ethereum) - } + if ShowGenesis { + utils.ShowGenesis(ethereum) + } if StartMining { utils.StartMining(ethereum) @@ -48,6 +48,6 @@ func main() { utils.StartEthereum(ethereum, UseSeed) // this blocks the thread - ethereum.WaitForShutdown() - ethlog.Flush() + ethereum.WaitForShutdown() + ethlog.Flush() } -- cgit v1.2.3 From e38b016547e98a33daf013c98c951254f95aeabf Mon Sep 17 00:00:00 2001 From: zelig Date: Sun, 29 Jun 2014 18:32:48 +0100 Subject: changed name for ethutil hex functions --- ethereum/javascript_runtime.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'ethereum') diff --git a/ethereum/javascript_runtime.go b/ethereum/javascript_runtime.go index 0dfe07a54..852a50487 100644 --- a/ethereum/javascript_runtime.go +++ b/ethereum/javascript_runtime.go @@ -122,12 +122,12 @@ out: } case object := <-self.changeChan: if stateObject, ok := object.Resource.(*ethchain.StateObject); ok { - for _, cb := range self.objectCb[ethutil.Hex(stateObject.Address())] { + for _, cb := range self.objectCb[ethutil.Bytes2Hex(stateObject.Address())] { val, _ := self.vm.ToValue(ethpub.NewPStateObject(stateObject)) cb.Call(cb, val) } } else if storageObject, ok := object.Resource.(*ethchain.StorageState); ok { - for _, cb := range self.objectCb[ethutil.Hex(storageObject.StateAddress)+ethutil.Hex(storageObject.Address)] { + for _, cb := range self.objectCb[ethutil.Bytes2Hex(storageObject.StateAddress)+ethutil.Bytes2Hex(storageObject.Address)] { val, _ := self.vm.ToValue(ethpub.NewPStorageState(storageObject)) cb.Call(cb, val) } @@ -178,12 +178,12 @@ func (self *JSRE) watch(call otto.FunctionCall) otto.Value { if storageCallback { self.objectCb[addr+storageAddr] = append(self.objectCb[addr+storageAddr], cb) - event := "storage:" + string(ethutil.FromHex(addr)) + ":" + string(ethutil.FromHex(storageAddr)) + event := "storage:" + string(ethutil.Hex2Bytes(addr)) + ":" + string(ethutil.Hex2Bytes(storageAddr)) self.ethereum.Reactor().Subscribe(event, self.changeChan) } else { self.objectCb[addr] = append(self.objectCb[addr], cb) - event := "object:" + string(ethutil.FromHex(addr)) + event := "object:" + string(ethutil.Hex2Bytes(addr)) self.ethereum.Reactor().Subscribe(event, self.changeChan) } @@ -221,7 +221,7 @@ func (self *JSRE) execBlock(call otto.FunctionCall) otto.Value { return otto.UndefinedValue() } - err = utils.BlockDo(self.ethereum, ethutil.FromHex(hash)) + err = utils.BlockDo(self.ethereum, ethutil.Hex2Bytes(hash)) if err != nil { fmt.Println(err) return otto.FalseValue() -- cgit v1.2.3 From 0ea9595d41c59d763237f7a3dd415f23dad34c6f Mon Sep 17 00:00:00 2001 From: zelig Date: Sun, 29 Jun 2014 18:33:22 +0100 Subject: new command line options - keyring: keyring/session identifier used by key manager - keystore: choice of db/file key storage - import message updated - export: name of directory to export keys to (was bool) --- ethereum/flags.go | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) (limited to 'ethereum') diff --git a/ethereum/flags.go b/ethereum/flags.go index 8fb87cf34..d5a9c3a8a 100644 --- a/ethereum/flags.go +++ b/ethereum/flags.go @@ -10,6 +10,8 @@ import ( ) var Identifier string +var KeyRing string +var KeyStore string var StartRpc bool var RpcPort int var UseUPnP bool @@ -19,8 +21,8 @@ var AddPeer string var MaxPeer int var GenAddr bool var UseSeed bool -var ImportKey string -var ExportKey bool +var SecretFile string +var ExportDir string var NonInteractive bool var Datadir string var LogFile string @@ -47,6 +49,8 @@ func Init() { } flag.StringVar(&Identifier, "id", "", "Custom client identifier") + flag.StringVar(&KeyRing, "keyring", "", "identifier for keyring to use") + flag.StringVar(&KeyStore, "keystore", "db", "system to store keyrings: db|file (db)") flag.StringVar(&OutboundPort, "port", "30303", "listening port") flag.BoolVar(&UseUPnP, "upnp", false, "enable UPnP support") flag.IntVar(&MaxPeer, "maxpeer", 10, "maximum desired peers") @@ -55,9 +59,9 @@ func Init() { flag.BoolVar(&NonInteractive, "y", false, "non-interactive mode (say yes to confirmations)") flag.BoolVar(&UseSeed, "seed", true, "seed peers") flag.BoolVar(&GenAddr, "genaddr", false, "create a new priv/pub key") - flag.BoolVar(&ExportKey, "export", false, "export private key") + flag.StringVar(&SecretFile, "import", "", "imports the file given (hex or mnemonic formats)") + flag.StringVar(&ExportDir, "export", "", "exports the session keyring to files in the directory given") flag.StringVar(&LogFile, "logfile", "", "log file (defaults to standard output)") - flag.StringVar(&ImportKey, "import", "", "imports the given private key (hex)") flag.StringVar(&Datadir, "datadir", defaultDataDir(), "specifies the datadir to use") flag.StringVar(&ConfigFile, "conf", defaultConfigFile, "config file") flag.StringVar(&DebugFile, "debug", "", "debug file (no debugging if not set)") -- cgit v1.2.3 From 27e1352c85e9b73fdccc83b559a104c68cc00975 Mon Sep 17 00:00:00 2001 From: zelig Date: Sun, 29 Jun 2014 18:37:22 +0100 Subject: main loop uses new flags and common methods in util: db, keymanager set up --- ethereum/main.go | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) (limited to 'ethereum') diff --git a/ethereum/main.go b/ethereum/main.go index 6b1995eec..1531871cb 100644 --- a/ethereum/main.go +++ b/ethereum/main.go @@ -21,10 +21,14 @@ func main() { utils.InitLogging(Datadir, LogFile, LogLevel, DebugFile) - ethereum := utils.NewEthereum(UseUPnP, OutboundPort, MaxPeer) + db := utils.NewDatabase() + + keyManager := utils.NewKeyManager(KeyStore, Datadir, db) // create, import, export keys - utils.KeyTasks(GenAddr, ImportKey, ExportKey, NonInteractive) + utils.KeyTasks(keyManager, KeyRing, GenAddr, SecretFile, ExportDir, NonInteractive) + + ethereum := utils.NewEthereum(db, keyManager, UseUPnP, OutboundPort, MaxPeer) if ShowGenesis { utils.ShowGenesis(ethereum) -- cgit v1.2.3