Merge pull request #1048 from ethersphere/cli-fixes

CLI, JSRE admin and  Solc improvements
pull/1062/head
Jeffrey Wilcke 10 years ago
commit 0300eef94d
  1. 25
      cmd/geth/admin.go
  2. 2
      cmd/geth/info_test.json
  3. 3
      cmd/geth/js.go
  4. 44
      cmd/geth/js_test.go
  5. 12
      cmd/geth/main.go
  6. 1
      cmd/utils/flags.go
  7. 110
      common/compiler/solidity.go
  8. 42
      common/compiler/solidity_test.go
  9. 20
      eth/backend.go
  10. 2536
      jsre/ethereum_js.go
  11. 1
      miner/worker.go
  12. 27
      rpc/api.go
  13. 44
      rpc/api_test.go
  14. 64
      rpc/args.go
  15. 19
      xeth/xeth.go

@ -35,6 +35,7 @@ func (js *jsre) adminBindings() {
eth := ethO.Object() eth := ethO.Object()
eth.Set("pendingTransactions", js.pendingTransactions) eth.Set("pendingTransactions", js.pendingTransactions)
eth.Set("resend", js.resend) eth.Set("resend", js.resend)
eth.Set("sign", js.sign)
js.re.Set("admin", struct{}{}) js.re.Set("admin", struct{}{})
t, _ := js.re.Get("admin") t, _ := js.re.Get("admin")
@ -177,6 +178,30 @@ func (js *jsre) resend(call otto.FunctionCall) otto.Value {
return otto.FalseValue() return otto.FalseValue()
} }
func (js *jsre) sign(call otto.FunctionCall) otto.Value {
if len(call.ArgumentList) != 2 {
fmt.Println("requires 2 arguments: eth.sign(signer, data)")
return otto.UndefinedValue()
}
signer, err := call.Argument(0).ToString()
if err != nil {
fmt.Println(err)
return otto.UndefinedValue()
}
data, err := call.Argument(1).ToString()
if err != nil {
fmt.Println(err)
return otto.UndefinedValue()
}
v, err := js.xeth.Sign(signer, data, false)
if err != nil {
fmt.Println(err)
return otto.UndefinedValue()
}
return js.re.ToVal(v)
}
func (js *jsre) debugBlock(call otto.FunctionCall) otto.Value { func (js *jsre) debugBlock(call otto.FunctionCall) otto.Value {
block, err := js.getBlock(call) block, err := js.getBlock(call)
if err != nil { if err != nil {

@ -1 +1 @@
{"code":"605280600c6000396000f3006000357c010000000000000000000000000000000000000000000000000000000090048063c6888fa114602e57005b60376004356041565b8060005260206000f35b6000600782029050604d565b91905056","info":{"abiDefinition":[{"constant":false,"inputs":[{"name":"a","type":"uint256"}],"name":"multiply","outputs":[{"name":"d","type":"uint256"}],"type":"function"}],"compilerVersion":"0.9.17","developerDoc":{"methods":{}},"language":"Solidity","languageVersion":"0","source":"contract test {\n /// @notice Will multiply `a` by 7.\n function multiply(uint a) returns(uint d) {\n return a * 7;\n }\n}\n","userDoc":{"methods":{"multiply(uint256)":{"notice":"Will multiply `a` by 7."}}}}} {"code":"0x605880600c6000396000f3006000357c010000000000000000000000000000000000000000000000000000000090048063c6888fa114602e57005b603d6004803590602001506047565b8060005260206000f35b60006007820290506053565b91905056","info":{"abiDefinition":[{"constant":false,"inputs":[{"name":"a","type":"uint256"}],"name":"multiply","outputs":[{"name":"d","type":"uint256"}],"type":"function"}],"compilerVersion":"0.9.23","developerDoc":{"methods":{}},"language":"Solidity","languageVersion":"0","source":"contract test {\n /// @notice Will multiply `a` by 7.\n function multiply(uint a) returns(uint d) {\n return a * 7;\n }\n}\n","userDoc":{"methods":{"multiply(uint256)":{"notice":"Will multiply `a` by 7."}}}}}

@ -71,7 +71,7 @@ type jsre struct {
prompter prompter
} }
func newJSRE(ethereum *eth.Ethereum, libPath, solcPath, corsDomain string, interactive bool, f xeth.Frontend) *jsre { func newJSRE(ethereum *eth.Ethereum, libPath, corsDomain string, interactive bool, f xeth.Frontend) *jsre {
js := &jsre{ethereum: ethereum, ps1: "> "} js := &jsre{ethereum: ethereum, ps1: "> "}
// set default cors domain used by startRpc from CLI flag // set default cors domain used by startRpc from CLI flag
js.corsDomain = corsDomain js.corsDomain = corsDomain
@ -81,7 +81,6 @@ func newJSRE(ethereum *eth.Ethereum, libPath, solcPath, corsDomain string, inter
js.xeth = xeth.New(ethereum, f) js.xeth = xeth.New(ethereum, f)
js.wait = js.xeth.UpdateState() js.wait = js.xeth.UpdateState()
// update state in separare forever blocks // update state in separare forever blocks
js.xeth.SetSolc(solcPath)
js.re = re.New(libPath) js.re = re.New(libPath)
js.apiBindings(f) js.apiBindings(f)
js.adminBindings() js.adminBindings()

@ -24,7 +24,7 @@ import (
const ( const (
testSolcPath = "" testSolcPath = ""
solcVersion = "0.9.17" solcVersion = "0.9.23"
testKey = "e6fab74a43941f82d89cb7faa408e227cdad3153c4720e540e855c19b15e6674" testKey = "e6fab74a43941f82d89cb7faa408e227cdad3153c4720e540e855c19b15e6674"
testAddress = "0x8605cdbbdb6d264aa742e77020dcbc58fcdce182" testAddress = "0x8605cdbbdb6d264aa742e77020dcbc58fcdce182"
@ -34,6 +34,7 @@ const (
) )
var ( var (
versionRE = regexp.MustCompile(strconv.Quote(`"compilerVersion":"` + solcVersion + `"`))
testGenesis = `{"` + testAddress[2:] + `": {"balance": "` + testBalance + `"}}` testGenesis = `{"` + testAddress[2:] + `": {"balance": "` + testBalance + `"}}`
) )
@ -75,6 +76,7 @@ func testJEthRE(t *testing.T) (string, *testjethre, *eth.Ethereum) {
AccountManager: am, AccountManager: am,
MaxPeers: 0, MaxPeers: 0,
Name: "test", Name: "test",
SolcPath: testSolcPath,
}) })
if err != nil { if err != nil {
t.Fatal("%v", err) t.Fatal("%v", err)
@ -101,7 +103,7 @@ func testJEthRE(t *testing.T) (string, *testjethre, *eth.Ethereum) {
t.Errorf("Error creating DocServer: %v", err) t.Errorf("Error creating DocServer: %v", err)
} }
tf := &testjethre{ds: ds, stateDb: ethereum.ChainManager().State().Copy()} tf := &testjethre{ds: ds, stateDb: ethereum.ChainManager().State().Copy()}
repl := newJSRE(ethereum, assetPath, testSolcPath, "", false, tf) repl := newJSRE(ethereum, assetPath, "", false, tf)
tf.jsre = repl tf.jsre = repl
return tmp, tf, ethereum return tmp, tf, ethereum
} }
@ -228,11 +230,11 @@ func TestSignature(t *testing.T) {
defer ethereum.Stop() defer ethereum.Stop()
defer os.RemoveAll(tmp) defer os.RemoveAll(tmp)
val, err := repl.re.Run(`eth.sign({from: "` + testAddress + `", data: "` + testHash + `"})`) val, err := repl.re.Run(`eth.sign("` + testAddress + `", "` + testHash + `")`)
// This is a very preliminary test, lacking actual signature verification // This is a very preliminary test, lacking actual signature verification
if err != nil { if err != nil {
t.Errorf("Error runnig js: %v", err) t.Errorf("Error running js: %v", err)
return return
} }
output := val.String() output := val.String()
@ -246,7 +248,6 @@ func TestSignature(t *testing.T) {
} }
func TestContract(t *testing.T) { func TestContract(t *testing.T) {
t.Skip()
tmp, repl, ethereum := testJEthRE(t) tmp, repl, ethereum := testJEthRE(t)
if err := ethereum.Start(); err != nil { if err := ethereum.Start(); err != nil {
@ -259,7 +260,9 @@ func TestContract(t *testing.T) {
var txc uint64 var txc uint64
coinbase := common.HexToAddress(testAddress) coinbase := common.HexToAddress(testAddress)
resolver.New(repl.xeth).CreateContracts(coinbase) resolver.New(repl.xeth).CreateContracts(coinbase)
// time.Sleep(1000 * time.Millisecond)
// checkEvalJSON(t, repl, `eth.getBlock("pending", true).transactions.length`, `2`)
source := `contract test {\n` + source := `contract test {\n` +
" /// @notice Will multiply `a` by 7." + `\n` + " /// @notice Will multiply `a` by 7." + `\n` +
` function multiply(uint a) returns(uint d) {\n` + ` function multiply(uint a) returns(uint d) {\n` +
@ -279,10 +282,9 @@ func TestContract(t *testing.T) {
// if solc is found with right version, test it, otherwise read from file // if solc is found with right version, test it, otherwise read from file
sol, err := compiler.New("") sol, err := compiler.New("")
if err != nil { if err != nil {
t.Logf("solc not found: skipping compiler test") t.Logf("solc not found: mocking contract compilation step")
} else if sol.Version() != solcVersion { } else if sol.Version() != solcVersion {
err = fmt.Errorf("solc wrong version found (%v, expect %v): skipping compiler test", sol.Version(), solcVersion) t.Logf("WARNING: solc different version found (%v, test written for %v, may need to update)", sol.Version(), solcVersion)
t.Log(err)
} }
if err != nil { if err != nil {
@ -295,10 +297,10 @@ func TestContract(t *testing.T) {
t.Errorf("%v", err) t.Errorf("%v", err)
} }
} else { } else {
checkEvalJSON(t, repl, `contract = eth.compile.solidity(source)`, string(contractInfo)) checkEvalJSON(t, repl, `contract = eth.compile.solidity(source).test`, string(contractInfo))
} }
checkEvalJSON(t, repl, `contract.code`, `"605280600c6000396000f3006000357c010000000000000000000000000000000000000000000000000000000090048063c6888fa114602e57005b60376004356041565b8060005260206000f35b6000600782029050604d565b91905056"`) checkEvalJSON(t, repl, `contract.code`, `"0x605880600c6000396000f3006000357c010000000000000000000000000000000000000000000000000000000090048063c6888fa114602e57005b603d6004803590602001506047565b8060005260206000f35b60006007820290506053565b91905056"`)
checkEvalJSON( checkEvalJSON(
t, repl, t, repl,
@ -308,15 +310,16 @@ func TestContract(t *testing.T) {
callSetup := `abiDef = JSON.parse('[{"constant":false,"inputs":[{"name":"a","type":"uint256"}],"name":"multiply","outputs":[{"name":"d","type":"uint256"}],"type":"function"}]'); callSetup := `abiDef = JSON.parse('[{"constant":false,"inputs":[{"name":"a","type":"uint256"}],"name":"multiply","outputs":[{"name":"d","type":"uint256"}],"type":"function"}]');
Multiply7 = eth.contract(abiDef); Multiply7 = eth.contract(abiDef);
multiply7 = new Multiply7(contractaddress); multiply7 = Multiply7.at(contractaddress);
` `
// time.Sleep(1500 * time.Millisecond)
_, err = repl.re.Run(callSetup) _, err = repl.re.Run(callSetup)
if err != nil { if err != nil {
t.Errorf("unexpected error registering, got %v", err) t.Errorf("unexpected error setting up contract, got %v", err)
} }
// updatespec // checkEvalJSON(t, repl, `eth.getBlock("pending", true).transactions.length`, `3`)
// why is this sometimes failing? // why is this sometimes failing?
// checkEvalJSON(t, repl, `multiply7.multiply.call(6)`, `42`) // checkEvalJSON(t, repl, `multiply7.multiply.call(6)`, `42`)
expNotice := "" expNotice := ""
@ -324,20 +327,23 @@ multiply7 = new Multiply7(contractaddress);
t.Errorf("incorrect confirmation message: expected %v, got %v", expNotice, repl.lastConfirm) t.Errorf("incorrect confirmation message: expected %v, got %v", expNotice, repl.lastConfirm)
} }
// why 0?
checkEvalJSON(t, repl, `eth.getBlock("pending", true).transactions.length`, `0`)
txc, repl.xeth = repl.xeth.ApplyTestTxs(repl.stateDb, coinbase, txc) txc, repl.xeth = repl.xeth.ApplyTestTxs(repl.stateDb, coinbase, txc)
checkEvalJSON(t, repl, `admin.contractInfo.start()`, `true`) checkEvalJSON(t, repl, `admin.contractInfo.start()`, `true`)
checkEvalJSON(t, repl, `multiply7.multiply.sendTransaction(6, { from: primary, gas: "1000000", gasPrice: "100000" })`, `undefined`) checkEvalJSON(t, repl, `multiply7.multiply.sendTransaction(6, { from: primary, gas: "1000000", gasPrice: "100000" })`, `undefined`)
expNotice = `About to submit transaction (no NatSpec info found for contract: content hash not found for '0x4a6c99e127191d2ee302e42182c338344b39a37a47cdbb17ab0f26b6802eb4d1'): {"params":[{"to":"0x5dcaace5982778b409c524873b319667eba5d074","data": "0xc6888fa10000000000000000000000000000000000000000000000000000000000000006"}]}` expNotice = `About to submit transaction (no NatSpec info found for contract: content hash not found for '0x87e2802265838c7f14bb69eecd2112911af6767907a702eeaa445239fb20711b'): {"params":[{"to":"0x5dcaace5982778b409c524873b319667eba5d074","data": "0xc6888fa10000000000000000000000000000000000000000000000000000000000000006"}]}`
if repl.lastConfirm != expNotice { if repl.lastConfirm != expNotice {
t.Errorf("incorrect confirmation message: expected %v, got %v", expNotice, repl.lastConfirm) t.Errorf("incorrect confirmation message: expected %v, got %v", expNotice, repl.lastConfirm)
} }
var contenthash = `"0x86d2b7cf1e72e9a7a3f8d96601f0151742a2f780f1526414304fbe413dc7f9bd"`
if sol != nil {
modContractInfo := versionRE.ReplaceAll(contractInfo, []byte(`"compilerVersion":"`+sol.Version()+`"`))
_ = modContractInfo
// contenthash = crypto.Sha3(modContractInfo)
}
checkEvalJSON(t, repl, `filename = "/tmp/info.json"`, `"/tmp/info.json"`) checkEvalJSON(t, repl, `filename = "/tmp/info.json"`, `"/tmp/info.json"`)
checkEvalJSON(t, repl, `contenthash = admin.contractInfo.register(primary, contractaddress, contract, filename)`, `"0x0d067e2dd99a4d8f0c0279738b17130dd415a89f24a23f0e7cf68c546ae3089d"`) checkEvalJSON(t, repl, `contenthash = admin.contractInfo.register(primary, contractaddress, contract, filename)`, contenthash)
checkEvalJSON(t, repl, `admin.contractInfo.registerUrl(primary, contenthash, "file://"+filename)`, `true`) checkEvalJSON(t, repl, `admin.contractInfo.registerUrl(primary, contenthash, "file://"+filename)`, `true`)
if err != nil { if err != nil {
t.Errorf("unexpected error registering, got %v", err) t.Errorf("unexpected error registering, got %v", err)

@ -99,7 +99,15 @@ The output of this command is supposed to be machine-readable.
Usage: "import ethereum presale wallet", Usage: "import ethereum presale wallet",
}, },
}, },
}, Description: `
get wallet import /path/to/my/presale.wallet
will prompt for your password and imports your ether presale account.
It can be used non-interactively with the --password option taking a
passwordfile as argument containing the wallet password in plaintext.
`},
{ {
Action: accountList, Action: accountList,
Name: "account", Name: "account",
@ -326,7 +334,6 @@ func console(ctx *cli.Context) {
repl := newJSRE( repl := newJSRE(
ethereum, ethereum,
ctx.String(utils.JSpathFlag.Name), ctx.String(utils.JSpathFlag.Name),
ctx.String(utils.SolcPathFlag.Name),
ctx.GlobalString(utils.RPCCORSDomainFlag.Name), ctx.GlobalString(utils.RPCCORSDomainFlag.Name),
true, true,
nil, nil,
@ -348,7 +355,6 @@ func execJSFiles(ctx *cli.Context) {
repl := newJSRE( repl := newJSRE(
ethereum, ethereum,
ctx.String(utils.JSpathFlag.Name), ctx.String(utils.JSpathFlag.Name),
ctx.String(utils.SolcPathFlag.Name),
ctx.GlobalString(utils.RPCCORSDomainFlag.Name), ctx.GlobalString(utils.RPCCORSDomainFlag.Name),
false, false,
nil, nil,

@ -313,6 +313,7 @@ func MakeEthConfig(clientID, version string, ctx *cli.Context) *eth.Config {
Dial: true, Dial: true,
BootNodes: ctx.GlobalString(BootnodesFlag.Name), BootNodes: ctx.GlobalString(BootnodesFlag.Name),
GasPrice: common.String2Big(ctx.GlobalString(GasPriceFlag.Name)), GasPrice: common.String2Big(ctx.GlobalString(GasPriceFlag.Name)),
SolcPath: ctx.GlobalString(SolcPathFlag.Name),
} }
} }

@ -18,7 +18,8 @@ import (
) )
const ( const (
flair = "Christian <c@ethdev.com> and Lefteris <lefteris@ethdev.com> (c) 2014-2015" // flair = "Christian <c@ethdev.com> and Lefteris <lefteris@ethdev.com> (c) 2014-2015"
flair = ""
languageVersion = "0" languageVersion = "0"
) )
@ -91,7 +92,7 @@ func (sol *Solidity) Version() string {
return sol.version return sol.version
} }
func (sol *Solidity) Compile(source string) (contract *Contract, err error) { func (sol *Solidity) Compile(source string) (contracts map[string]*Contract, err error) {
if len(source) == 0 { if len(source) == 0 {
err = fmt.Errorf("empty source") err = fmt.Errorf("empty source")
@ -122,58 +123,61 @@ func (sol *Solidity) Compile(source string) (contract *Contract, err error) {
err = fmt.Errorf("solc error: missing code output") err = fmt.Errorf("solc error: missing code output")
return return
} }
if len(matches) > 1 {
err = fmt.Errorf("multi-contract sources are not supported")
return
}
_, file := filepath.Split(matches[0])
base := strings.Split(file, ".")[0]
codeFile := filepath.Join(wd, base+".binary")
abiDefinitionFile := filepath.Join(wd, base+".abi")
userDocFile := filepath.Join(wd, base+".docuser")
developerDocFile := filepath.Join(wd, base+".docdev")
code, err := ioutil.ReadFile(codeFile) contracts = make(map[string]*Contract)
if err != nil { for _, path := range matches {
err = fmt.Errorf("error reading compiler output for code: %v", err) _, file := filepath.Split(path)
return base := strings.Split(file, ".")[0]
}
abiDefinitionJson, err := ioutil.ReadFile(abiDefinitionFile) codeFile := filepath.Join(wd, base+".binary")
if err != nil { abiDefinitionFile := filepath.Join(wd, base+".abi")
err = fmt.Errorf("error reading compiler output for abiDefinition: %v", err) userDocFile := filepath.Join(wd, base+".docuser")
return developerDocFile := filepath.Join(wd, base+".docdev")
}
var abiDefinition interface{} var code, abiDefinitionJson, userDocJson, developerDocJson []byte
err = json.Unmarshal(abiDefinitionJson, &abiDefinition) code, err = ioutil.ReadFile(codeFile)
if err != nil {
userDocJson, err := ioutil.ReadFile(userDocFile) err = fmt.Errorf("error reading compiler output for code: %v", err)
if err != nil { return
err = fmt.Errorf("error reading compiler output for userDoc: %v", err) }
return abiDefinitionJson, err = ioutil.ReadFile(abiDefinitionFile)
} if err != nil {
var userDoc interface{} err = fmt.Errorf("error reading compiler output for abiDefinition: %v", err)
err = json.Unmarshal(userDocJson, &userDoc) return
}
developerDocJson, err := ioutil.ReadFile(developerDocFile) var abiDefinition interface{}
if err != nil { err = json.Unmarshal(abiDefinitionJson, &abiDefinition)
err = fmt.Errorf("error reading compiler output for developerDoc: %v", err)
return userDocJson, err = ioutil.ReadFile(userDocFile)
} if err != nil {
var developerDoc interface{} err = fmt.Errorf("error reading compiler output for userDoc: %v", err)
err = json.Unmarshal(developerDocJson, &developerDoc) return
}
contract = &Contract{ var userDoc interface{}
Code: string(code), err = json.Unmarshal(userDocJson, &userDoc)
Info: ContractInfo{
Source: source, developerDocJson, err = ioutil.ReadFile(developerDocFile)
Language: "Solidity", if err != nil {
LanguageVersion: languageVersion, err = fmt.Errorf("error reading compiler output for developerDoc: %v", err)
CompilerVersion: sol.version, return
AbiDefinition: abiDefinition, }
UserDoc: userDoc, var developerDoc interface{}
DeveloperDoc: developerDoc, err = json.Unmarshal(developerDocJson, &developerDoc)
},
contract := &Contract{
Code: "0x" + string(code),
Info: ContractInfo{
Source: source,
Language: "Solidity",
LanguageVersion: languageVersion,
CompilerVersion: sol.version,
AbiDefinition: abiDefinition,
UserDoc: userDoc,
DeveloperDoc: developerDoc,
},
}
contracts[base] = contract
} }
return return

@ -9,7 +9,7 @@ import (
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
) )
const solcVersion = "0.9.17" const solcVersion = "0.9.23"
var ( var (
source = ` source = `
@ -20,37 +20,45 @@ contract test {
} }
} }
` `
code = "605280600c6000396000f3006000357c010000000000000000000000000000000000000000000000000000000090048063c6888fa114602e57005b60376004356041565b8060005260206000f35b6000600782029050604d565b91905056" code = "0x605880600c6000396000f3006000357c010000000000000000000000000000000000000000000000000000000090048063c6888fa114602e57005b603d6004803590602001506047565b8060005260206000f35b60006007820290506053565b91905056"
info = `{"source":"\ncontract test {\n /// @notice Will multiply ` + "`a`" + ` by 7.\n function multiply(uint a) returns(uint d) {\n return a * 7;\n }\n}\n","language":"Solidity","languageVersion":"0","compilerVersion":"0.9.17","abiDefinition":[{"constant":false,"inputs":[{"name":"a","type":"uint256"}],"name":"multiply","outputs":[{"name":"d","type":"uint256"}],"type":"function"}],"userDoc":{"methods":{"multiply(uint256)":{"notice":"Will multiply ` + "`a`" + ` by 7."}}},"developerDoc":{"methods":{}}}` info = `{"source":"\ncontract test {\n /// @notice Will multiply ` + "`a`" + ` by 7.\n function multiply(uint a) returns(uint d) {\n return a * 7;\n }\n}\n","language":"Solidity","languageVersion":"0","compilerVersion":"0.9.23","abiDefinition":[{"constant":false,"inputs":[{"name":"a","type":"uint256"}],"name":"multiply","outputs":[{"name":"d","type":"uint256"}],"type":"function"}],"userDoc":{"methods":{"multiply(uint256)":{"notice":"Will multiply ` + "`a`" + ` by 7."}}},"developerDoc":{"methods":{}}}`
infohash = common.HexToHash("0x834075768a68e500e459b9c3213750c84de3df47156500cb01bb664d3f88c60a") infohash = common.HexToHash("0xea782f674eb898e477c20e8a7cf11c2c28b09fa68b5278732104f7a101aed255")
) )
func TestCompiler(t *testing.T) { func TestCompiler(t *testing.T) {
sol, err := New("") sol, err := New("")
if err != nil { if err != nil {
t.Skip("no solc installed") t.Skip("solc not found: skip")
} else if sol.Version() != solcVersion {
t.Logf("WARNING: a newer version of solc found (%v, expect %v)", sol.Version(), solcVersion)
} }
contract, err := sol.Compile(source) contracts, err := sol.Compile(source)
if err != nil { if err != nil {
t.Errorf("error compiling source. result %v: %v", contract, err) t.Errorf("error compiling source. result %v: %v", contracts, err)
return return
} }
/*
if contract.Code != code { if len(contracts) != 1 {
t.Errorf("wrong code, expected\n%s, got\n%s", code, contract.Code) t.Errorf("one contract expected, got\n%s", len(contracts))
} }
*/
if contracts["test"].Code != code {
t.Errorf("wrong code, expected\n%s, got\n%s", code, contracts["test"].Code)
}
} }
func TestCompileError(t *testing.T) { func TestCompileError(t *testing.T) {
sol, err := New("") sol, err := New("")
if err != nil || sol.version != solcVersion { if err != nil || sol.version != solcVersion {
t.Skip("no solc installed") t.Skip("solc not found: skip")
} else if sol.Version() != solcVersion {
t.Logf("WARNING: a newer version of solc found (%v, expect %v)", sol.Version(), solcVersion)
} }
contract, err := sol.Compile(source[2:]) contracts, err := sol.Compile(source[2:])
if err == nil { if err == nil {
t.Errorf("error expected compiling source. got none. result %v", contract) t.Errorf("error expected compiling source. got none. result %v", contracts)
return return
} }
} }
@ -78,11 +86,11 @@ func TestExtractInfo(t *testing.T) {
os.Remove(filename) os.Remove(filename)
cinfohash, err := ExtractInfo(contract, filename) cinfohash, err := ExtractInfo(contract, filename)
if err != nil { if err != nil {
t.Errorf("%v", err) t.Errorf("error extracting info: %v", err)
} }
got, err := ioutil.ReadFile(filename) got, err := ioutil.ReadFile(filename)
if err != nil { if err != nil {
t.Errorf("%v", err) t.Errorf("error reading '%v': %v", filename, err)
} }
if string(got) != info { if string(got) != info {
t.Errorf("incorrect info.json extracted, expected:\n%s\ngot\n%s", info, string(got)) t.Errorf("incorrect info.json extracted, expected:\n%s\ngot\n%s", info, string(got))

@ -14,6 +14,7 @@ import (
"github.com/ethereum/ethash" "github.com/ethereum/ethash"
"github.com/ethereum/go-ethereum/accounts" "github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/compiler"
"github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm" "github.com/ethereum/go-ethereum/core/vm"
@ -79,6 +80,7 @@ type Config struct {
GasPrice *big.Int GasPrice *big.Int
MinerThreads int MinerThreads int
AccountManager *accounts.Manager AccountManager *accounts.Manager
SolcPath string
// NewDB is used to create databases. // NewDB is used to create databases.
// If nil, the default is to create leveldb databases on disk. // If nil, the default is to create leveldb databases on disk.
@ -181,6 +183,8 @@ type Ethereum struct {
pow *ethash.Ethash pow *ethash.Ethash
protocolManager *ProtocolManager protocolManager *ProtocolManager
downloader *downloader.Downloader downloader *downloader.Downloader
SolcPath string
solc *compiler.Solidity
net *p2p.Server net *p2p.Server
eventMux *event.TypeMux eventMux *event.TypeMux
@ -264,6 +268,7 @@ func New(config *Config) (*Ethereum, error) {
netVersionId: config.NetworkId, netVersionId: config.NetworkId,
NatSpec: config.NatSpec, NatSpec: config.NatSpec,
MinerThreads: config.MinerThreads, MinerThreads: config.MinerThreads,
SolcPath: config.SolcPath,
} }
eth.pow = ethash.New() eth.pow = ethash.New()
@ -571,3 +576,18 @@ func saveBlockchainVersion(db common.Database, bcVersion int) {
db.Put([]byte("BlockchainVersion"), common.NewValue(bcVersion).Bytes()) db.Put([]byte("BlockchainVersion"), common.NewValue(bcVersion).Bytes())
} }
} }
func (self *Ethereum) Solc() (*compiler.Solidity, error) {
var err error
if self.solc == nil {
self.solc, err = compiler.New(self.SolcPath)
}
return self.solc, err
}
// set in js console via admin interface or wrapper from cli flags
func (self *Ethereum) SetSolc(solcPath string) (*compiler.Solidity, error) {
self.SolcPath = solcPath
self.solc = nil
return self.Solc()
}

File diff suppressed because it is too large Load Diff

@ -270,6 +270,7 @@ func (self *worker) makeCurrent() {
} }
block.Header().Extra = self.extra block.Header().Extra = self.extra
// when 08 is processed ancestors contain 07 (quick block)
current := env(block, self.eth) current := env(block, self.eth)
for _, ancestor := range self.chain.GetAncestors(block, 7) { for _, ancestor := range self.chain.GetAncestors(block, 7) {
for _, uncle := range ancestor.Uncles() { for _, uncle := range ancestor.Uncles() {

@ -158,16 +158,16 @@ func (api *EthereumApi) GetRequestReply(req *RpcRequest, reply *interface{}) err
v := api.xethAtStateNum(args.BlockNumber).CodeAtBytes(args.Address) v := api.xethAtStateNum(args.BlockNumber).CodeAtBytes(args.Address)
*reply = newHexData(v) *reply = newHexData(v)
case "eth_sign": // case "eth_sign":
args := new(NewSigArgs) // args := new(NewSigArgs)
if err := json.Unmarshal(req.Params, &args); err != nil { // if err := json.Unmarshal(req.Params, &args); err != nil {
return err // return err
} // }
v, err := api.xeth().Sign(args.From, args.Data, false) // v, err := api.xeth().Sign(args.From, args.Data, false)
if err != nil { // if err != nil {
return err // return err
} // }
*reply = v // *reply = v
case "eth_sendTransaction", "eth_transact": case "eth_sendTransaction", "eth_transact":
args := new(NewTxArgs) args := new(NewTxArgs)
@ -347,7 +347,7 @@ func (api *EthereumApi) GetRequestReply(req *RpcRequest, reply *interface{}) err
solc, _ := api.xeth().Solc() solc, _ := api.xeth().Solc()
if solc == nil { if solc == nil {
return NewNotImplementedError(req.Method) return NewNotAvailableError(req.Method, "solc (solidity compiler) not found")
} }
args := new(SourceArgs) args := new(SourceArgs)
@ -355,12 +355,11 @@ func (api *EthereumApi) GetRequestReply(req *RpcRequest, reply *interface{}) err
return err return err
} }
contract, err := solc.Compile(args.Source) contracts, err := solc.Compile(args.Source)
if err != nil { if err != nil {
return err return err
} }
contract.Code = newHexData(contract.Code).String() *reply = contracts
*reply = contract
case "eth_newFilter": case "eth_newFilter":
args := new(BlockFilterArgs) args := new(BlockFilterArgs)

@ -2,14 +2,11 @@ package rpc
import ( import (
"encoding/json" "encoding/json"
// "sync"
"testing"
// "time"
// "fmt"
"io/ioutil"
"strconv" "strconv"
"testing"
"github.com/ethereum/go-ethereum/common/compiler" "github.com/ethereum/go-ethereum/common/compiler"
"github.com/ethereum/go-ethereum/eth"
"github.com/ethereum/go-ethereum/xeth" "github.com/ethereum/go-ethereum/xeth"
) )
@ -30,12 +27,15 @@ func TestWeb3Sha3(t *testing.T) {
} }
} }
const solcVersion = "0.9.23"
func TestCompileSolidity(t *testing.T) { func TestCompileSolidity(t *testing.T) {
t.Skip()
solc, err := compiler.New("") solc, err := compiler.New("")
if solc == nil { if solc == nil {
t.Skip("no solidity compiler") t.Skip("no solc found: skip")
} else if solc.Version() != solcVersion {
t.Logf("WARNING: solc different version found (%v, test written for %v, may need to update)", solc.Version(), solcVersion)
} }
source := `contract test {\n` + source := `contract test {\n` +
" /// @notice Will multiply `a` by 7." + `\n` + " /// @notice Will multiply `a` by 7." + `\n` +
@ -46,16 +46,16 @@ func TestCompileSolidity(t *testing.T) {
jsonstr := `{"jsonrpc":"2.0","method":"eth_compileSolidity","params":["` + source + `"],"id":64}` jsonstr := `{"jsonrpc":"2.0","method":"eth_compileSolidity","params":["` + source + `"],"id":64}`
//expCode := "605280600c6000396000f3006000357c010000000000000000000000000000000000000000000000000000000090048063c6888fa114602e57005b60376004356041565b8060005260206000f35b6000600782029050604d565b91905056" expCode := "0x605880600c6000396000f3006000357c010000000000000000000000000000000000000000000000000000000090048063c6888fa114602e57005b603d6004803590602001506047565b8060005260206000f35b60006007820290506053565b91905056"
expAbiDefinition := `[{"constant":false,"inputs":[{"name":"a","type":"uint256"}],"name":"multiply","outputs":[{"name":"d","type":"uint256"}],"type":"function"}]` expAbiDefinition := `[{"constant":false,"inputs":[{"name":"a","type":"uint256"}],"name":"multiply","outputs":[{"name":"d","type":"uint256"}],"type":"function"}]`
expUserDoc := `{"methods":{"multiply(uint256)":{"notice":"Will multiply ` + "`a`" + ` by 7."}}}` expUserDoc := `{"methods":{"multiply(uint256)":{"notice":"Will multiply ` + "`a`" + ` by 7."}}}`
expDeveloperDoc := `{"methods":{}}` expDeveloperDoc := `{"methods":{}}`
expCompilerVersion := `0.9.13` expCompilerVersion := solc.Version()
expLanguage := "Solidity" expLanguage := "Solidity"
expLanguageVersion := "0" expLanguageVersion := "0"
expSource := source expSource := source
api := NewEthereumApi(&xeth.XEth{}) api := NewEthereumApi(xeth.NewTest(&eth.Ethereum{}, nil))
var req RpcRequest var req RpcRequest
json.Unmarshal([]byte(jsonstr), &req) json.Unmarshal([]byte(jsonstr), &req)
@ -70,26 +70,34 @@ func TestCompileSolidity(t *testing.T) {
t.Errorf("expected no error, got %v", err) t.Errorf("expected no error, got %v", err)
} }
var contract = compiler.Contract{} var contracts = make(map[string]*compiler.Contract)
err = json.Unmarshal(respjson, &contract) err = json.Unmarshal(respjson, &contracts)
if err != nil { if err != nil {
t.Errorf("expected no error, got %v", err) t.Errorf("expected no error, got %v", err)
} }
/* if len(contracts) != 1 {
if contract.Code != expCode { t.Errorf("expected one contract, got %v", len(contracts))
t.Errorf("Expected %s got %s", expCode, contract.Code) }
}
*/ contract := contracts["test"]
if contract.Code != expCode {
t.Errorf("Expected \n%s got \n%s", expCode, contract.Code)
}
if strconv.Quote(contract.Info.Source) != `"`+expSource+`"` { if strconv.Quote(contract.Info.Source) != `"`+expSource+`"` {
t.Errorf("Expected \n'%s' got \n'%s'", expSource, strconv.Quote(contract.Info.Source)) t.Errorf("Expected \n'%s' got \n'%s'", expSource, strconv.Quote(contract.Info.Source))
} }
if contract.Info.Language != expLanguage { if contract.Info.Language != expLanguage {
t.Errorf("Expected %s got %s", expLanguage, contract.Info.Language) t.Errorf("Expected %s got %s", expLanguage, contract.Info.Language)
} }
if contract.Info.LanguageVersion != expLanguageVersion { if contract.Info.LanguageVersion != expLanguageVersion {
t.Errorf("Expected %s got %s", expLanguageVersion, contract.Info.LanguageVersion) t.Errorf("Expected %s got %s", expLanguageVersion, contract.Info.LanguageVersion)
} }
if contract.Info.CompilerVersion != expCompilerVersion { if contract.Info.CompilerVersion != expCompilerVersion {
t.Errorf("Expected %s got %s", expCompilerVersion, contract.Info.CompilerVersion) t.Errorf("Expected %s got %s", expCompilerVersion, contract.Info.CompilerVersion)
} }
@ -112,8 +120,6 @@ func TestCompileSolidity(t *testing.T) {
if string(abidef) != expAbiDefinition { if string(abidef) != expAbiDefinition {
t.Errorf("Expected \n'%s' got \n'%s'", expAbiDefinition, string(abidef)) t.Errorf("Expected \n'%s' got \n'%s'", expAbiDefinition, string(abidef))
} }
ioutil.WriteFile("/tmp/abidef", []byte(string(abidef)), 0700)
ioutil.WriteFile("/tmp/expabidef", []byte(expAbiDefinition), 0700)
if string(userdoc) != expUserDoc { if string(userdoc) != expUserDoc {
t.Errorf("Expected \n'%s' got \n'%s'", expUserDoc, string(userdoc)) t.Errorf("Expected \n'%s' got \n'%s'", expUserDoc, string(userdoc))

@ -166,45 +166,45 @@ type NewTxArgs struct {
BlockNumber int64 BlockNumber int64
} }
type NewSigArgs struct { // type NewSigArgs struct {
From string // From string
Data string // Data string
} // }
func (args *NewSigArgs) UnmarshalJSON(b []byte) (err error) { // func (args *NewSigArgs) UnmarshalJSON(b []byte) (err error) {
var obj []json.RawMessage // var obj []json.RawMessage
var ext struct { // var ext struct {
From string // From string
Data string // Data string
} // }
// Decode byte slice to array of RawMessages // // Decode byte slice to array of RawMessages
if err := json.Unmarshal(b, &obj); err != nil { // if err := json.Unmarshal(b, &obj); err != nil {
return NewDecodeParamError(err.Error()) // return NewDecodeParamError(err.Error())
} // }
// Check for sufficient params // // Check for sufficient params
if len(obj) < 1 { // if len(obj) < 1 {
return NewInsufficientParamsError(len(obj), 1) // return NewInsufficientParamsError(len(obj), 1)
} // }
// Decode 0th RawMessage to temporary struct // // Decode 0th RawMessage to temporary struct
if err := json.Unmarshal(obj[0], &ext); err != nil { // if err := json.Unmarshal(obj[0], &ext); err != nil {
return NewDecodeParamError(err.Error()) // return NewDecodeParamError(err.Error())
} // }
if len(ext.From) == 0 { // if len(ext.From) == 0 {
return NewValidationError("from", "is required") // return NewValidationError("from", "is required")
} // }
if len(ext.Data) == 0 { // if len(ext.Data) == 0 {
return NewValidationError("data", "is required") // return NewValidationError("data", "is required")
} // }
args.From = ext.From // args.From = ext.From
args.Data = ext.Data // args.Data = ext.Data
return nil // return nil
} // }
func (args *NewTxArgs) UnmarshalJSON(b []byte) (err error) { func (args *NewTxArgs) UnmarshalJSON(b []byte) (err error) {
var obj []json.RawMessage var obj []json.RawMessage

@ -66,12 +66,16 @@ type XEth struct {
// regmut sync.Mutex // regmut sync.Mutex
// register map[string][]*interface{} // TODO improve return type // register map[string][]*interface{} // TODO improve return type
solcPath string
solc *compiler.Solidity
agent *miner.RemoteAgent agent *miner.RemoteAgent
} }
func NewTest(eth *eth.Ethereum, frontend Frontend) *XEth {
return &XEth{
backend: eth,
frontend: frontend,
}
}
// New creates an XEth that uses the given frontend. // New creates an XEth that uses the given frontend.
// If a nil Frontend is provided, a default frontend which // If a nil Frontend is provided, a default frontend which
// confirms all transactions will be used. // confirms all transactions will be used.
@ -379,17 +383,12 @@ func (self *XEth) Accounts() []string {
// accessor for solidity compiler. // accessor for solidity compiler.
// memoized if available, retried on-demand if not // memoized if available, retried on-demand if not
func (self *XEth) Solc() (*compiler.Solidity, error) { func (self *XEth) Solc() (*compiler.Solidity, error) {
var err error return self.backend.Solc()
if self.solc == nil {
self.solc, err = compiler.New(self.solcPath)
}
return self.solc, err
} }
// set in js console via admin interface or wrapper from cli flags // set in js console via admin interface or wrapper from cli flags
func (self *XEth) SetSolc(solcPath string) (*compiler.Solidity, error) { func (self *XEth) SetSolc(solcPath string) (*compiler.Solidity, error) {
self.solcPath = solcPath self.backend.SetSolc(solcPath)
self.solc = nil
return self.Solc() return self.Solc()
} }

Loading…
Cancel
Save