Skip to content

Commit 1e806c4

Browse files
committed
cmd, common, core, eth, node, rpc, tests, whisper, xeth: use protocol stacks
1 parent 8a44451 commit 1e806c4

30 files changed

Lines changed: 1041 additions & 939 deletions

‎cmd/geth/js.go‎

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ import (
3434
"github.com/ethereum/go-ethereum/common/registrar"
3535
"github.com/ethereum/go-ethereum/eth"
3636
re "github.com/ethereum/go-ethereum/jsre"
37+
"github.com/ethereum/go-ethereum/node"
3738
"github.com/ethereum/go-ethereum/rpc"
3839
"github.com/ethereum/go-ethereum/rpc/api"
3940
"github.com/ethereum/go-ethereum/rpc/codec"
@@ -77,7 +78,7 @@ func (r dumbterm) AppendHistory(string) {}
7778

7879
type jsre struct {
7980
re *re.JSRE
80-
ethereum *eth.Ethereum
81+
stack *node.Node
8182
xeth *xeth.XEth
8283
wait chan *big.Int
8384
ps1 string
@@ -176,18 +177,18 @@ func newLightweightJSRE(docRoot string, client comms.EthereumClient, datadir str
176177
return js
177178
}
178179

179-
func newJSRE(ethereum *eth.Ethereum, docRoot, corsDomain string, client comms.EthereumClient, interactive bool, f xeth.Frontend) *jsre {
180-
js := &jsre{ethereum: ethereum, ps1: "> "}
180+
func newJSRE(stack *node.Node, docRoot, corsDomain string, client comms.EthereumClient, interactive bool, f xeth.Frontend) *jsre {
181+
js := &jsre{stack: stack, ps1: "> "}
181182
// set default cors domain used by startRpc from CLI flag
182183
js.corsDomain = corsDomain
183184
if f == nil {
184185
f = js
185186
}
186-
js.xeth = xeth.New(ethereum, f)
187+
js.xeth = xeth.New(stack, f)
187188
js.wait = js.xeth.UpdateState()
188189
js.client = client
189190
if clt, ok := js.client.(*comms.InProcClient); ok {
190-
if offeredApis, err := api.ParseApiString(shared.AllApis, codec.JSON, js.xeth, ethereum); err == nil {
191+
if offeredApis, err := api.ParseApiString(shared.AllApis, codec.JSON, js.xeth, stack); err == nil {
191192
clt.Initialize(api.Merge(offeredApis...))
192193
}
193194
}
@@ -202,14 +203,14 @@ func newJSRE(ethereum *eth.Ethereum, docRoot, corsDomain string, client comms.Et
202203
js.prompter = dumbterm{bufio.NewReader(os.Stdin)}
203204
} else {
204205
lr := liner.NewLiner()
205-
js.withHistory(ethereum.DataDir, func(hist *os.File) { lr.ReadHistory(hist) })
206+
js.withHistory(stack.DataDir(), func(hist *os.File) { lr.ReadHistory(hist) })
206207
lr.SetCtrlCAborts(true)
207208
js.loadAutoCompletion()
208209
lr.SetWordCompleter(apiWordCompleter)
209210
lr.SetTabCompletionStyle(liner.TabPrints)
210211
js.prompter = lr
211212
js.atexit = func() {
212-
js.withHistory(ethereum.DataDir, func(hist *os.File) { hist.Truncate(0); lr.WriteHistory(hist) })
213+
js.withHistory(stack.DataDir(), func(hist *os.File) { hist.Truncate(0); lr.WriteHistory(hist) })
213214
lr.Close()
214215
close(js.wait)
215216
}
@@ -276,7 +277,7 @@ func (js *jsre) apiBindings(f xeth.Frontend) error {
276277
apiNames = append(apiNames, a)
277278
}
278279

279-
apiImpl, err := api.ParseApiString(strings.Join(apiNames, ","), codec.JSON, js.xeth, js.ethereum)
280+
apiImpl, err := api.ParseApiString(strings.Join(apiNames, ","), codec.JSON, js.xeth, js.stack)
280281
if err != nil {
281282
utils.Fatalf("Unable to determine supported api's: %v", err)
282283
}
@@ -342,8 +343,14 @@ func (self *jsre) AskPassword() (string, bool) {
342343
}
343344

344345
func (self *jsre) ConfirmTransaction(tx string) bool {
345-
if self.ethereum.NatSpec {
346-
notice := natspec.GetNotice(self.xeth, tx, self.ethereum.HTTPClient())
346+
// Retrieve the Ethereum instance from the node
347+
var ethereum *eth.Ethereum
348+
if _, err := self.stack.SingletonService(&ethereum); err != nil {
349+
return false
350+
}
351+
// If natspec is enabled, ask for permission
352+
if ethereum.NatSpec {
353+
notice := natspec.GetNotice(self.xeth, tx, ethereum.HTTPClient())
347354
fmt.Println(notice)
348355
answer, _ := self.Prompt("Confirm Transaction [y/n]")
349356
return strings.HasPrefix(strings.Trim(answer, " "), "y")
@@ -359,7 +366,11 @@ func (self *jsre) UnlockAccount(addr []byte) bool {
359366
return false
360367
}
361368
// TODO: allow retry
362-
if err := self.ethereum.AccountManager().Unlock(common.BytesToAddress(addr), pass); err != nil {
369+
var ethereum *eth.Ethereum
370+
if _, err := self.stack.SingletonService(&ethereum); err != nil {
371+
return false
372+
}
373+
if err := ethereum.AccountManager().Unlock(common.BytesToAddress(addr), pass); err != nil {
363374
return false
364375
} else {
365376
fmt.Println("Account is now unlocked for this session.")

‎cmd/geth/js_test.go‎

Lines changed: 63 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ import (
3838
"github.com/ethereum/go-ethereum/crypto"
3939
"github.com/ethereum/go-ethereum/eth"
4040
"github.com/ethereum/go-ethereum/ethdb"
41+
"github.com/ethereum/go-ethereum/node"
4142
"github.com/ethereum/go-ethereum/rpc/codec"
4243
"github.com/ethereum/go-ethereum/rpc/comms"
4344
)
@@ -66,75 +67,85 @@ type testjethre struct {
6667
}
6768

6869
func (self *testjethre) UnlockAccount(acc []byte) bool {
69-
err := self.ethereum.AccountManager().Unlock(common.BytesToAddress(acc), "")
70+
var ethereum *eth.Ethereum
71+
self.stack.SingletonService(&ethereum)
72+
73+
err := ethereum.AccountManager().Unlock(common.BytesToAddress(acc), "")
7074
if err != nil {
7175
panic("unable to unlock")
7276
}
7377
return true
7478
}
7579

7680
func (self *testjethre) ConfirmTransaction(tx string) bool {
77-
if self.ethereum.NatSpec {
81+
var ethereum *eth.Ethereum
82+
self.stack.SingletonService(&ethereum)
83+
84+
if ethereum.NatSpec {
7885
self.lastConfirm = natspec.GetNotice(self.xeth, tx, self.client)
7986
}
8087
return true
8188
}
8289

83-
func testJEthRE(t *testing.T) (string, *testjethre, *eth.Ethereum) {
90+
func testJEthRE(t *testing.T) (string, *testjethre, *node.Node) {
8491
return testREPL(t, nil)
8592
}
8693

87-
func testREPL(t *testing.T, config func(*eth.Config)) (string, *testjethre, *eth.Ethereum) {
94+
func testREPL(t *testing.T, config func(*eth.Config)) (string, *testjethre, *node.Node) {
8895
tmp, err := ioutil.TempDir("", "geth-test")
8996
if err != nil {
9097
t.Fatal(err)
9198
}
99+
// Create a networkless protocol stack
100+
stack, err := node.New(&node.Config{PrivateKey: testNodeKey, Name: "test", NoDiscovery: true})
101+
if err != nil {
102+
t.Fatalf("failed to create node: %v", err)
103+
}
104+
// Initialize and register the Ethereum protocol
105+
keystore := crypto.NewKeyStorePlain(filepath.Join(tmp, "keystore"))
106+
accman := accounts.NewManager(keystore)
92107

93108
db, _ := ethdb.NewMemDatabase()
94-
95109
core.WriteGenesisBlockForTesting(db, core.GenesisAccount{common.HexToAddress(testAddress), common.String2Big(testBalance)})
96-
ks := crypto.NewKeyStorePlain(filepath.Join(tmp, "keystore"))
97-
am := accounts.NewManager(ks)
98-
conf := &eth.Config{
99-
NodeKey: testNodeKey,
100-
DataDir: tmp,
101-
AccountManager: am,
102-
MaxPeers: 0,
103-
Name: "test",
104-
DocRoot: "/",
105-
SolcPath: testSolcPath,
106-
PowTest: true,
107-
NewDB: func(path string) (ethdb.Database, error) { return db, nil },
110+
111+
ethConf := &eth.Config{
112+
TestGenesisState: db,
113+
AccountManager: accman,
114+
DocRoot: "/",
115+
SolcPath: testSolcPath,
116+
PowTest: true,
108117
}
109118
if config != nil {
110-
config(conf)
119+
config(ethConf)
111120
}
112-
ethereum, err := eth.New(conf)
113-
if err != nil {
114-
t.Fatal("%v", err)
121+
if err := stack.Register("ethereum", func(ctx *node.ServiceContext) (node.Service, error) { return eth.New(ctx, ethConf) }); err != nil {
122+
t.Fatalf("failed to register ethereum protocol: %v", err)
115123
}
116-
124+
// Initialize all the keys for testing
117125
keyb, err := crypto.HexToECDSA(testKey)
118126
if err != nil {
119127
t.Fatal(err)
120128
}
121129
key := crypto.NewKeyFromECDSA(keyb)
122-
err = ks.StoreKey(key, "")
123-
if err != nil {
130+
if err := keystore.StoreKey(key, ""); err != nil {
124131
t.Fatal(err)
125132
}
126-
127-
err = am.Unlock(key.Address, "")
128-
if err != nil {
133+
if err := accman.Unlock(key.Address, ""); err != nil {
129134
t.Fatal(err)
130135
}
136+
// Start the node and assemble the REPL tester
137+
if err := stack.Start(); err != nil {
138+
t.Fatalf("failed to start test stack: %v", err)
139+
}
140+
var ethereum *eth.Ethereum
141+
stack.SingletonService(&ethereum)
131142

132143
assetPath := filepath.Join(os.Getenv("GOPATH"), "src", "github.com", "ethereum", "go-ethereum", "cmd", "mist", "assets", "ext")
133144
client := comms.NewInProcClient(codec.JSON)
134145
tf := &testjethre{client: ethereum.HTTPClient()}
135-
repl := newJSRE(ethereum, assetPath, "", client, false, tf)
146+
repl := newJSRE(stack, assetPath, "", client, false, tf)
136147
tf.jsre = repl
137-
return tmp, tf, ethereum
148+
return tmp, tf, stack
138149
}
139150

140151
func TestNodeInfo(t *testing.T) {
@@ -151,11 +162,8 @@ func TestNodeInfo(t *testing.T) {
151162
}
152163

153164
func TestAccounts(t *testing.T) {
154-
tmp, repl, ethereum := testJEthRE(t)
155-
if err := ethereum.Start(); err != nil {
156-
t.Fatalf("error starting ethereum: %v", err)
157-
}
158-
defer ethereum.Stop()
165+
tmp, repl, node := testJEthRE(t)
166+
defer node.Stop()
159167
defer os.RemoveAll(tmp)
160168

161169
checkEvalJSON(t, repl, `eth.accounts`, `["`+testAddress+`"]`)
@@ -174,11 +182,8 @@ func TestAccounts(t *testing.T) {
174182
}
175183

176184
func TestBlockChain(t *testing.T) {
177-
tmp, repl, ethereum := testJEthRE(t)
178-
if err := ethereum.Start(); err != nil {
179-
t.Fatalf("error starting ethereum: %v", err)
180-
}
181-
defer ethereum.Stop()
185+
tmp, repl, node := testJEthRE(t)
186+
defer node.Stop()
182187
defer os.RemoveAll(tmp)
183188
// get current block dump before export/import.
184189
val, err := repl.re.Run("JSON.stringify(debug.dumpBlock(eth.blockNumber))")
@@ -196,6 +201,8 @@ func TestBlockChain(t *testing.T) {
196201
tmpfile := filepath.Join(extmp, "export.chain")
197202
tmpfileq := strconv.Quote(tmpfile)
198203

204+
var ethereum *eth.Ethereum
205+
node.SingletonService(&ethereum)
199206
ethereum.BlockChain().Reset()
200207

201208
checkEvalJSON(t, repl, `admin.exportChain(`+tmpfileq+`)`, `true`)
@@ -209,22 +216,15 @@ func TestBlockChain(t *testing.T) {
209216
}
210217

211218
func TestMining(t *testing.T) {
212-
tmp, repl, ethereum := testJEthRE(t)
213-
if err := ethereum.Start(); err != nil {
214-
t.Fatalf("error starting ethereum: %v", err)
215-
}
216-
defer ethereum.Stop()
219+
tmp, repl, node := testJEthRE(t)
220+
defer node.Stop()
217221
defer os.RemoveAll(tmp)
218222
checkEvalJSON(t, repl, `eth.mining`, `false`)
219223
}
220224

221225
func TestRPC(t *testing.T) {
222-
tmp, repl, ethereum := testJEthRE(t)
223-
if err := ethereum.Start(); err != nil {
224-
t.Errorf("error starting ethereum: %v", err)
225-
return
226-
}
227-
defer ethereum.Stop()
226+
tmp, repl, node := testJEthRE(t)
227+
defer node.Stop()
228228
defer os.RemoveAll(tmp)
229229

230230
checkEvalJSON(t, repl, `admin.startRPC("127.0.0.1", 5004, "*", "web3,eth,net")`, `true`)
@@ -234,25 +234,17 @@ func TestCheckTestAccountBalance(t *testing.T) {
234234
t.Skip() // i don't think it tests the correct behaviour here. it's actually testing
235235
// internals which shouldn't be tested. This now fails because of a change in the core
236236
// and i have no means to fix this, sorry - @obscuren
237-
tmp, repl, ethereum := testJEthRE(t)
238-
if err := ethereum.Start(); err != nil {
239-
t.Errorf("error starting ethereum: %v", err)
240-
return
241-
}
242-
defer ethereum.Stop()
237+
tmp, repl, node := testJEthRE(t)
238+
defer node.Stop()
243239
defer os.RemoveAll(tmp)
244240

245241
repl.re.Run(`primary = "` + testAddress + `"`)
246242
checkEvalJSON(t, repl, `eth.getBalance(primary)`, `"`+testBalance+`"`)
247243
}
248244

249245
func TestSignature(t *testing.T) {
250-
tmp, repl, ethereum := testJEthRE(t)
251-
if err := ethereum.Start(); err != nil {
252-
t.Errorf("error starting ethereum: %v", err)
253-
return
254-
}
255-
defer ethereum.Stop()
246+
tmp, repl, node := testJEthRE(t)
247+
defer node.Stop()
256248
defer os.RemoveAll(tmp)
257249

258250
val, err := repl.re.Run(`eth.sign("` + testAddress + `", "` + testHash + `")`)
@@ -443,7 +435,10 @@ multiply7 = Multiply7.at(contractaddress);
443435
}
444436

445437
func pendingTransactions(repl *testjethre, t *testing.T) (txc int64, err error) {
446-
txs := repl.ethereum.TxPool().GetTransactions()
438+
var ethereum *eth.Ethereum
439+
repl.stack.SingletonService(&ethereum)
440+
441+
txs := ethereum.TxPool().GetTransactions()
447442
return int64(len(txs)), nil
448443
}
449444

@@ -468,12 +463,15 @@ func processTxs(repl *testjethre, t *testing.T, expTxc int) bool {
468463
t.Errorf("incorrect number of pending transactions, expected %v, got %v", expTxc, txc)
469464
return false
470465
}
471-
err = repl.ethereum.StartMining(runtime.NumCPU(), "")
466+
var ethereum *eth.Ethereum
467+
repl.stack.SingletonService(&ethereum)
468+
469+
err = ethereum.StartMining(runtime.NumCPU(), "")
472470
if err != nil {
473471
t.Errorf("unexpected error mining: %v", err)
474472
return false
475473
}
476-
defer repl.ethereum.StopMining()
474+
defer ethereum.StopMining()
477475

478476
timer := time.NewTimer(100 * time.Second)
479477
height := new(big.Int).Add(repl.xeth.CurrentBlock().Number(), big.NewInt(1))

0 commit comments

Comments
 (0)