Merge branch 'poc-9' into develop

This commit is contained in:
obscuren 2015-03-10 11:25:32 +01:00
commit c0a8e3cd34
5 changed files with 198 additions and 137 deletions

View File

@ -87,6 +87,11 @@ runtime will execute the file and exit.
Name: "import", Name: "import",
Usage: `import a blockchain file`, Usage: `import a blockchain file`,
}, },
{
Action: exportchain,
Name: "export",
Usage: `export blockchain into file`,
},
} }
app.Author = "" app.Author = ""
app.Email = "" app.Email = ""
@ -171,25 +176,39 @@ func importchain(ctx *cli.Context) {
if len(ctx.Args()) != 1 { if len(ctx.Args()) != 1 {
utils.Fatalf("This command requires an argument.") utils.Fatalf("This command requires an argument.")
} }
chain, _, _ := utils.GetChain(ctx) chainmgr, _, _ := utils.GetChain(ctx)
start := time.Now() start := time.Now()
err := utils.ImportChain(chain, ctx.Args().First()) err := utils.ImportChain(chainmgr, ctx.Args().First())
if err != nil { if err != nil {
utils.Fatalf("Import error: %v\n", err) utils.Fatalf("Import error: %v\n", err)
} }
fmt.Printf("Import done in", time.Since(start)) fmt.Printf("Import done in %v", time.Since(start))
return
}
func exportchain(ctx *cli.Context) {
if len(ctx.Args()) != 1 {
utils.Fatalf("This command requires an argument.")
}
chainmgr, _, _ := utils.GetChain(ctx)
start := time.Now()
err := utils.ExportChain(chainmgr, ctx.Args().First())
if err != nil {
utils.Fatalf("Export error: %v\n", err)
}
fmt.Printf("Export done in %v", time.Since(start))
return return
} }
func dump(ctx *cli.Context) { func dump(ctx *cli.Context) {
chain, _, stateDb := utils.GetChain(ctx) chainmgr, _, stateDb := utils.GetChain(ctx)
for _, arg := range ctx.Args() { for _, arg := range ctx.Args() {
var block *types.Block var block *types.Block
if hashish(arg) { if hashish(arg) {
block = chain.GetBlock(ethutil.Hex2Bytes(arg)) block = chainmgr.GetBlock(ethutil.Hex2Bytes(arg))
} else { } else {
num, _ := strconv.Atoi(arg) num, _ := strconv.Atoi(arg)
block = chain.GetBlockByNumber(uint64(num)) block = chainmgr.GetBlockByNumber(uint64(num))
} }
if block == nil { if block == nil {
fmt.Println("{}") fmt.Println("{}")
@ -209,11 +228,13 @@ func hashish(x string) bool {
} }
func version(c *cli.Context) { func version(c *cli.Context) {
fmt.Printf(`%v %v fmt.Printf(`%v
PV=%d Version: %v
GOOS=%s Protocol Version: %d
GO=%s Network Id: %d
GO: %s
OS: %s
GOPATH=%s GOPATH=%s
GOROOT=%s GOROOT=%s
`, ClientIdentifier, Version, eth.ProtocolVersion, runtime.GOOS, runtime.Version(), os.Getenv("GOPATH"), runtime.GOROOT()) `, ClientIdentifier, Version, eth.ProtocolVersion, eth.NetworkId, runtime.Version(), runtime.GOOS, os.Getenv("GOPATH"), runtime.GOROOT())
} }

View File

@ -35,7 +35,6 @@ import (
"github.com/ethereum/go-ethereum/logger" "github.com/ethereum/go-ethereum/logger"
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
rpchttp "github.com/ethereum/go-ethereum/rpc/http" rpchttp "github.com/ethereum/go-ethereum/rpc/http"
"github.com/ethereum/go-ethereum/state"
"github.com/ethereum/go-ethereum/xeth" "github.com/ethereum/go-ethereum/xeth"
) )
@ -188,27 +187,8 @@ func FormatTransactionData(data string) []byte {
return d return d
} }
// Replay block func ImportChain(chainmgr *core.ChainManager, fn string) error {
func BlockDo(ethereum *eth.Ethereum, hash []byte) error { fmt.Printf("importing blockchain '%s'\n", fn)
block := ethereum.ChainManager().GetBlock(hash)
if block == nil {
return fmt.Errorf("unknown block %x", hash)
}
parent := ethereum.ChainManager().GetBlock(block.ParentHash())
statedb := state.New(parent.Root(), ethereum.StateDb())
_, err := ethereum.BlockProcessor().TransitionState(statedb, parent, block, true)
if err != nil {
return err
}
return nil
}
func ImportChain(chain *core.ChainManager, fn string) error {
fmt.Printf("importing chain '%s'\n", fn)
fh, err := os.OpenFile(fn, os.O_RDONLY, os.ModePerm) fh, err := os.OpenFile(fn, os.O_RDONLY, os.ModePerm)
if err != nil { if err != nil {
return err return err
@ -220,11 +200,24 @@ func ImportChain(chain *core.ChainManager, fn string) error {
return err return err
} }
chain.Reset() chainmgr.Reset()
if err := chain.InsertChain(blocks); err != nil { if err := chainmgr.InsertChain(blocks); err != nil {
return err return err
} }
fmt.Printf("imported %d blocks\n", len(blocks)) fmt.Printf("imported %d blocks\n", len(blocks))
return nil return nil
} }
func ExportChain(chainmgr *core.ChainManager, fn string) error {
fmt.Printf("exporting blockchain '%s'\n", fn)
data := chainmgr.Export()
if err := ethutil.WriteFile(fn, data); err != nil {
return err
}
fmt.Printf("exported blockchain\n")
return nil
}

View File

@ -1,24 +1,21 @@
package natspec package natspec
import ( import (
"fmt"
"github.com/obscuren/otto" "github.com/obscuren/otto"
"io/ioutil"
) )
type NatSpec struct { type NatSpec struct {
jsvm *otto.Otto jsvm *otto.Otto
} }
func NewNATSpec(transaction string) (self *NatSpec, err error) { // TODO: should initialise with abi and userdoc jsons
func New() (self *NatSpec, err error) {
self = new(NatSpec) self = new(NatSpec)
self.jsvm = otto.New() self.jsvm = otto.New()
code, err := ioutil.ReadFile("natspec.js")
if err != nil {
return
}
_, err = self.jsvm.Run(string(code)) _, err = self.jsvm.Run(natspecJS)
if err != nil { if err != nil {
return return
} }
@ -27,39 +24,40 @@ func NewNATSpec(transaction string) (self *NatSpec, err error) {
return return
} }
self.jsvm.Run("var transaction = " + transaction + ";")
return return
} }
func (self *NatSpec) SetDescription(desc string) (err error) { func (self *NatSpec) Notice(transaction, abi, method, expression string) (string, error) {
var err error
if _, err = self.jsvm.Run("var transaction = " + transaction + ";"); err != nil {
return "", fmt.Errorf("natspec.js error setting transaction: %v", err)
}
_, err = self.jsvm.Run("var expression = \"" + desc + "\";") if _, err = self.jsvm.Run("var abi = " + abi + ";"); err != nil {
return return "", fmt.Errorf("natspec.js error setting abi: %v", err)
}
} if _, err = self.jsvm.Run("var method = '" + method + "';"); err != nil {
return "", fmt.Errorf("natspec.js error setting method: %v", err)
}
func (self *NatSpec) SetABI(abi string) (err error) { if _, err = self.jsvm.Run("var expression = \"" + expression + "\";"); err != nil {
return "", fmt.Errorf("natspec.js error setting expression: %v", err)
_, err = self.jsvm.Run("var abi = " + abi + ";") }
return
}
func (self *NatSpec) SetMethod(method string) (err error) {
_, err = self.jsvm.Run("var method = '" + method + "';")
return
}
func (self *NatSpec) Parse() string {
self.jsvm.Run("var call = {method: method,abi: abi,transaction: transaction};") self.jsvm.Run("var call = {method: method,abi: abi,transaction: transaction};")
value, err := self.jsvm.Run("natspec.evaluateExpression(expression, call);") value, err := self.jsvm.Run("natspec.evaluateExpression(expression, call);")
if err != nil { if err != nil {
return err.Error() return "", fmt.Errorf("natspec.js error evaluating expression: %v", err)
} }
return value.String() evalError := "Natspec evaluation failed, wrong input params"
if value.String() == evalError {
return "", fmt.Errorf("natspec.js error evaluating expression: wrong input params in expression '%s'", expression)
}
if len(value.String()) == 0 {
return "", fmt.Errorf("natspec.js error evaluating expression")
}
return value.String(), nil
} }

View File

@ -1,4 +1,6 @@
require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ package natspec
const natspecJS = `require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
},{}],2:[function(require,module,exports){ },{}],2:[function(require,module,exports){
// shim for using process in browser // shim for using process in browser
@ -3452,8 +3454,8 @@ var natspec = (function () {
var mapExpressionsToEvaluate = function (expression, cb) { var mapExpressionsToEvaluate = function (expression, cb) {
var evaluatedExpression = ""; var evaluatedExpression = "";
// match everything in `` quotes // match everything in backtick
var pattern = /\`(?:\\.|[^`\\])*\`/gim var pattern = /\` + "`" + `(?:\\.|[^` + "`" + `\\])*\` + "`" + `/gim
var match; var match;
var lastIndex = 0; var lastIndex = 0;
while ((match = pattern.exec(expression)) !== null) { while ((match = pattern.exec(expression)) !== null) {
@ -3515,3 +3517,4 @@ module.exports = natspec;
},{"./node_modules/ethereum.js/lib/abi.js":3}]},{},[]); },{"./node_modules/ethereum.js/lib/abi.js":3}]},{},[]);
`

View File

@ -6,7 +6,7 @@ import (
func TestNotice(t *testing.T) { func TestNotice(t *testing.T) {
ns, err := NewNATSpec(` tx := `
{ {
"jsonrpc": "2.0", "jsonrpc": "2.0",
"method": "eth_call", "method": "eth_call",
@ -16,13 +16,9 @@ func TestNotice(t *testing.T) {
}], }],
"id": 6 "id": 6
} }
`) `
if err != nil { abi := `
t.Errorf("NewNATSpec error %v", err)
}
ns.SetABI(`
[{ [{
"name": "multiply", "name": "multiply",
"constant": false, "constant": false,
@ -36,11 +32,22 @@ func TestNotice(t *testing.T) {
"type": "uint256" "type": "uint256"
}] }]
}] }]
`) `
ns.SetDescription("Will multiply `a` by 7 and return `a * 7`.")
ns.SetMethod("multiply")
notice := ns.Parse() desc := "Will multiply `a` by 7 and return `a * 7`."
method := "multiply"
ns, err := New()
if err != nil {
t.Errorf("NewNATSpec error %v", err)
}
notice, err := ns.Notice(tx, abi, method, desc)
if err != nil {
t.Errorf("expected no error got %v", err)
}
expected := "Will multiply 122 by 7 and return 854." expected := "Will multiply 122 by 7 and return 854."
if notice != expected { if notice != expected {
@ -48,4 +55,43 @@ func TestNotice(t *testing.T) {
} else { } else {
t.Logf("returned notice \"%v\"", notice) t.Logf("returned notice \"%v\"", notice)
} }
notice, err = ns.Notice(tx, abi, method, "Will multiply 122 by \"7\" and return 854.")
expected = "natspec.js error setting expression: (anonymous): Line 1:41 Unexpected number"
if err == nil {
t.Errorf("expected error, got nothing (notice: '%v')", err, notice)
} else {
if err.Error() != expected {
t.Errorf("expected error '%s' got '%v' (notice: '%v')", expected, err, notice)
}
}
// https://github.com/ethereum/natspec.js/issues/1
// badDesc := "Will multiply `e` by 7 and return `a * 7`."
// notice, err = ns.Notice(tx, abi, method, badDesc)
// expected = "natspec.js error evaluating expression: wrong input param in expression ''"
// if err == nil {
// t.Errorf("expected error, got nothing (notice: '%v')", notice)
// } else {
// if err.Error() != expected {
// t.Errorf("expected error '%s' got '%v' (notice: '%v')", expected, err, notice)
// }
// }
notice, err = ns.Notice(tx, abi, "missing_method", desc)
expected = "natspec.js error evaluating expression: wrong input params in expression 'Will multiply `a` by 7 and return `a * 7`.'"
if err == nil {
t.Errorf("expected error, got nothing (notice: '%v')", notice)
} else {
if err.Error() != expected {
t.Errorf("expected error '%s' got '%v' (notice: '%v')", expected, err, notice)
}
}
} }