admin.go 12.7 KB
Newer Older
F
Felix Lange 已提交
1
// Copyright 2015 The go-ethereum Authors
2
// This file is part of the go-ethereum library.
F
Felix Lange 已提交
3
//
4
// The go-ethereum library is free software: you can redistribute it and/or modify
F
Felix Lange 已提交
5 6 7 8
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
9
// The go-ethereum library is distributed in the hope that it will be useful,
F
Felix Lange 已提交
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
F
Felix Lange 已提交
12 13 14
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
15
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
F
Felix Lange 已提交
16

B
Bas van Kervel 已提交
17 18 19 20 21
package api

import (
	"fmt"
	"io"
Z
zelig 已提交
22
	"math/big"
B
Bas van Kervel 已提交
23
	"os"
Z
zelig 已提交
24
	"time"
B
Bas van Kervel 已提交
25

Z
zelig 已提交
26 27 28 29
	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/common/compiler"
	"github.com/ethereum/go-ethereum/common/natspec"
	"github.com/ethereum/go-ethereum/common/registrar"
B
Bas van Kervel 已提交
30 31
	"github.com/ethereum/go-ethereum/core"
	"github.com/ethereum/go-ethereum/core/types"
Z
zelig 已提交
32
	"github.com/ethereum/go-ethereum/crypto"
B
Bas van Kervel 已提交
33 34
	"github.com/ethereum/go-ethereum/eth"
	"github.com/ethereum/go-ethereum/logger/glog"
35
	"github.com/ethereum/go-ethereum/p2p"
B
Bas van Kervel 已提交
36 37
	"github.com/ethereum/go-ethereum/rlp"
	"github.com/ethereum/go-ethereum/rpc/codec"
B
Bas van Kervel 已提交
38
	"github.com/ethereum/go-ethereum/rpc/comms"
B
Bas van Kervel 已提交
39
	"github.com/ethereum/go-ethereum/rpc/shared"
B
Bas van Kervel 已提交
40
	"github.com/ethereum/go-ethereum/rpc/useragent"
B
Bas van Kervel 已提交
41 42 43 44
	"github.com/ethereum/go-ethereum/xeth"
)

const (
45
	AdminApiversion = "1.0"
B
Bas van Kervel 已提交
46 47 48 49 50 51
	importBatchSize = 2500
)

var (
	// mapping between methods and handlers
	AdminMapping = map[string]adminhandler{
Z
zelig 已提交
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
		"admin_addPeer":            (*adminApi).AddPeer,
		"admin_peers":              (*adminApi).Peers,
		"admin_nodeInfo":           (*adminApi).NodeInfo,
		"admin_exportChain":        (*adminApi).ExportChain,
		"admin_importChain":        (*adminApi).ImportChain,
		"admin_verbosity":          (*adminApi).Verbosity,
		"admin_setSolc":            (*adminApi).SetSolc,
		"admin_datadir":            (*adminApi).DataDir,
		"admin_startRPC":           (*adminApi).StartRPC,
		"admin_stopRPC":            (*adminApi).StopRPC,
		"admin_setGlobalRegistrar": (*adminApi).SetGlobalRegistrar,
		"admin_setHashReg":         (*adminApi).SetHashReg,
		"admin_setUrlHint":         (*adminApi).SetUrlHint,
		"admin_saveInfo":           (*adminApi).SaveInfo,
		"admin_register":           (*adminApi).Register,
		"admin_registerUrl":        (*adminApi).RegisterUrl,
		"admin_startNatSpec":       (*adminApi).StartNatSpec,
		"admin_stopNatSpec":        (*adminApi).StopNatSpec,
		"admin_getContractInfo":    (*adminApi).GetContractInfo,
		"admin_httpGet":            (*adminApi).HttpGet,
Z
zelig 已提交
72 73
		"admin_sleepBlocks":        (*adminApi).SleepBlocks,
		"admin_sleep":              (*adminApi).Sleep,
B
Bas van Kervel 已提交
74
		"admin_enableUserAgent":    (*adminApi).EnableUserAgent,
B
Bas van Kervel 已提交
75 76 77 78 79 80 81 82 83
	}
)

// admin callback handler
type adminhandler func(*adminApi, *shared.Request) (interface{}, error)

// admin api provider
type adminApi struct {
	xeth     *xeth.XEth
84
	network  *p2p.Server
B
Bas van Kervel 已提交
85
	ethereum *eth.Ethereum
B
Bas van Kervel 已提交
86 87
	codec    codec.Codec
	coder    codec.ApiCoder
B
Bas van Kervel 已提交
88 89 90
}

// create a new admin api instance
91
func NewAdminApi(xeth *xeth.XEth, network *p2p.Server, ethereum *eth.Ethereum, codec codec.Codec) *adminApi {
B
Bas van Kervel 已提交
92 93
	return &adminApi{
		xeth:     xeth,
94
		network:  network,
B
Bas van Kervel 已提交
95
		ethereum: ethereum,
B
Bas van Kervel 已提交
96 97
		codec:    codec,
		coder:    codec.New(nil),
B
Bas van Kervel 已提交
98 99 100 101 102
	}
}

// collection with supported methods
func (self *adminApi) Methods() []string {
B
Bas van Kervel 已提交
103
	methods := make([]string, len(AdminMapping))
B
Bas van Kervel 已提交
104
	i := 0
B
Bas van Kervel 已提交
105
	for k := range AdminMapping {
B
Bas van Kervel 已提交
106 107 108 109 110 111 112 113
		methods[i] = k
		i++
	}
	return methods
}

// Execute given request
func (self *adminApi) Execute(req *shared.Request) (interface{}, error) {
B
Bas van Kervel 已提交
114
	if callback, ok := AdminMapping[req.Method]; ok {
B
Bas van Kervel 已提交
115 116 117 118 119 120 121
		return callback(self, req)
	}

	return nil, &shared.NotImplementedError{req.Method}
}

func (self *adminApi) Name() string {
B
Bas van Kervel 已提交
122
	return shared.AdminApiName
B
Bas van Kervel 已提交
123 124
}

125 126 127 128
func (self *adminApi) ApiVersion() string {
	return AdminApiversion
}

B
Bas van Kervel 已提交
129 130
func (self *adminApi) AddPeer(req *shared.Request) (interface{}, error) {
	args := new(AddPeerArgs)
B
Bas van Kervel 已提交
131
	if err := self.coder.Decode(req.Params, &args); err != nil {
B
Bas van Kervel 已提交
132 133 134 135 136 137 138 139 140 141 142
		return nil, shared.NewDecodeParamError(err.Error())
	}

	err := self.ethereum.AddPeer(args.Url)
	if err == nil {
		return true, nil
	}
	return false, err
}

func (self *adminApi) Peers(req *shared.Request) (interface{}, error) {
143
	return self.network.PeersInfo(), nil
B
Bas van Kervel 已提交
144 145 146
}

func (self *adminApi) NodeInfo(req *shared.Request) (interface{}, error) {
147
	return self.network.NodeInfo(), nil
B
Bas van Kervel 已提交
148 149
}

B
Bas van Kervel 已提交
150 151 152 153
func (self *adminApi) DataDir(req *shared.Request) (interface{}, error) {
	return self.ethereum.DataDir, nil
}

154
func hasAllBlocks(chain *core.BlockChain, bs []*types.Block) bool {
B
Bas van Kervel 已提交
155 156 157 158 159 160 161 162 163 164
	for _, b := range bs {
		if !chain.HasBlock(b.Hash()) {
			return false
		}
	}
	return true
}

func (self *adminApi) ImportChain(req *shared.Request) (interface{}, error) {
	args := new(ImportExportChainArgs)
B
Bas van Kervel 已提交
165
	if err := self.coder.Decode(req.Params, &args); err != nil {
B
Bas van Kervel 已提交
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
		return nil, shared.NewDecodeParamError(err.Error())
	}

	fh, err := os.Open(args.Filename)
	if err != nil {
		return false, err
	}
	defer fh.Close()
	stream := rlp.NewStream(fh, 0)

	// Run actual the import.
	blocks := make(types.Blocks, importBatchSize)
	n := 0
	for batch := 0; ; batch++ {

		i := 0
		for ; i < importBatchSize; i++ {
			var b types.Block
			if err := stream.Decode(&b); err == io.EOF {
				break
			} else if err != nil {
				return false, fmt.Errorf("at block %d: %v", n, err)
			}
			blocks[i] = &b
			n++
		}
		if i == 0 {
			break
		}
		// Import the batch.
196
		if hasAllBlocks(self.ethereum.BlockChain(), blocks[:i]) {
B
Bas van Kervel 已提交
197 198
			continue
		}
199
		if _, err := self.ethereum.BlockChain().InsertChain(blocks[:i]); err != nil {
B
Bas van Kervel 已提交
200 201 202 203 204 205 206 207
			return false, fmt.Errorf("invalid block %d: %v", n, err)
		}
	}
	return true, nil
}

func (self *adminApi) ExportChain(req *shared.Request) (interface{}, error) {
	args := new(ImportExportChainArgs)
B
Bas van Kervel 已提交
208
	if err := self.coder.Decode(req.Params, &args); err != nil {
B
Bas van Kervel 已提交
209 210 211 212 213 214 215 216
		return nil, shared.NewDecodeParamError(err.Error())
	}

	fh, err := os.OpenFile(args.Filename, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm)
	if err != nil {
		return false, err
	}
	defer fh.Close()
217
	if err := self.ethereum.BlockChain().Export(fh); err != nil {
B
Bas van Kervel 已提交
218 219 220 221 222 223 224 225
		return false, err
	}

	return true, nil
}

func (self *adminApi) Verbosity(req *shared.Request) (interface{}, error) {
	args := new(VerbosityArgs)
B
Bas van Kervel 已提交
226
	if err := self.coder.Decode(req.Params, &args); err != nil {
B
Bas van Kervel 已提交
227 228 229 230 231 232 233 234 235
		return nil, shared.NewDecodeParamError(err.Error())
	}

	glog.SetV(args.Level)
	return true, nil
}

func (self *adminApi) SetSolc(req *shared.Request) (interface{}, error) {
	args := new(SetSolcArgs)
B
Bas van Kervel 已提交
236
	if err := self.coder.Decode(req.Params, &args); err != nil {
B
Bas van Kervel 已提交
237 238 239 240 241 242 243 244 245
		return nil, shared.NewDecodeParamError(err.Error())
	}

	solc, err := self.xeth.SetSolc(args.Path)
	if err != nil {
		return nil, err
	}
	return solc.Info(), nil
}
B
Bas van Kervel 已提交
246 247 248 249 250 251 252 253 254 255 256 257 258

func (self *adminApi) StartRPC(req *shared.Request) (interface{}, error) {
	args := new(StartRPCArgs)
	if err := self.coder.Decode(req.Params, &args); err != nil {
		return nil, shared.NewDecodeParamError(err.Error())
	}

	cfg := comms.HttpConfig{
		ListenAddress: args.ListenAddress,
		ListenPort:    args.ListenPort,
		CorsDomain:    args.CorsDomain,
	}

Z
zelig 已提交
259
	apis, err := ParseApiString(args.Apis, self.codec, self.xeth, self.ethereum)
260 261
	if err != nil {
		return false, err
B
Bas van Kervel 已提交
262 263
	}

264
	err = comms.StartHttp(cfg, self.codec, Merge(apis...))
B
Bas van Kervel 已提交
265 266 267 268 269 270 271 272 273 274
	if err == nil {
		return true, nil
	}
	return false, err
}

func (self *adminApi) StopRPC(req *shared.Request) (interface{}, error) {
	comms.StopHttp()
	return true, nil
}
Z
zelig 已提交
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312

func (self *adminApi) SleepBlocks(req *shared.Request) (interface{}, error) {
	args := new(SleepBlocksArgs)
	if err := self.coder.Decode(req.Params, &args); err != nil {
		return nil, shared.NewDecodeParamError(err.Error())
	}
	var timer <-chan time.Time
	var height *big.Int
	var err error
	if args.Timeout > 0 {
		timer = time.NewTimer(time.Duration(args.Timeout) * time.Second).C
	}

	height = new(big.Int).Add(self.xeth.CurrentBlock().Number(), big.NewInt(args.N))
	height, err = sleepBlocks(self.xeth.UpdateState(), height, timer)
	if err != nil {
		return nil, err
	}
	return height.Uint64(), nil
}

func sleepBlocks(wait chan *big.Int, height *big.Int, timer <-chan time.Time) (newHeight *big.Int, err error) {
	wait <- height
	select {
	case <-timer:
		// if times out make sure the xeth loop does not block
		go func() {
			select {
			case wait <- nil:
			case <-wait:
			}
		}()
		return nil, fmt.Errorf("timeout")
	case newHeight = <-wait:
	}
	return
}

Z
zelig 已提交
313 314 315 316 317 318 319 320 321
func (self *adminApi) Sleep(req *shared.Request) (interface{}, error) {
	args := new(SleepArgs)
	if err := self.coder.Decode(req.Params, &args); err != nil {
		return nil, shared.NewDecodeParamError(err.Error())
	}
	time.Sleep(time.Duration(args.S) * time.Second)
	return nil, nil
}

Z
zelig 已提交
322 323 324 325 326 327 328 329 330
func (self *adminApi) SetGlobalRegistrar(req *shared.Request) (interface{}, error) {
	args := new(SetGlobalRegistrarArgs)
	if err := self.coder.Decode(req.Params, &args); err != nil {
		return nil, shared.NewDecodeParamError(err.Error())
	}

	sender := common.HexToAddress(args.ContractAddress)

	reg := registrar.New(self.xeth)
331
	txhash, err := reg.SetGlobalRegistrar(args.NameReg, sender)
Z
zelig 已提交
332 333 334 335
	if err != nil {
		return false, err
	}

336
	return txhash, nil
Z
zelig 已提交
337 338 339 340 341 342 343 344 345 346
}

func (self *adminApi) SetHashReg(req *shared.Request) (interface{}, error) {
	args := new(SetHashRegArgs)
	if err := self.coder.Decode(req.Params, &args); err != nil {
		return nil, shared.NewDecodeParamError(err.Error())
	}

	reg := registrar.New(self.xeth)
	sender := common.HexToAddress(args.Sender)
347
	txhash, err := reg.SetHashReg(args.HashReg, sender)
Z
zelig 已提交
348 349 350 351
	if err != nil {
		return false, err
	}

352
	return txhash, nil
Z
zelig 已提交
353 354 355 356 357 358 359 360 361 362 363 364
}

func (self *adminApi) SetUrlHint(req *shared.Request) (interface{}, error) {
	args := new(SetUrlHintArgs)
	if err := self.coder.Decode(req.Params, &args); err != nil {
		return nil, shared.NewDecodeParamError(err.Error())
	}

	urlHint := args.UrlHint
	sender := common.HexToAddress(args.Sender)

	reg := registrar.New(self.xeth)
365
	txhash, err := reg.SetUrlHint(urlHint, sender)
Z
zelig 已提交
366 367 368 369
	if err != nil {
		return nil, err
	}

370
	return txhash, nil
Z
zelig 已提交
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
}

func (self *adminApi) SaveInfo(req *shared.Request) (interface{}, error) {
	args := new(SaveInfoArgs)
	if err := self.coder.Decode(req.Params, &args); err != nil {
		return nil, shared.NewDecodeParamError(err.Error())
	}

	contenthash, err := compiler.SaveInfo(&args.ContractInfo, args.Filename)
	if err != nil {
		return nil, err
	}

	return contenthash.Hex(), nil
}

func (self *adminApi) Register(req *shared.Request) (interface{}, error) {
	args := new(RegisterArgs)
	if err := self.coder.Decode(req.Params, &args); err != nil {
		return nil, shared.NewDecodeParamError(err.Error())
	}

	sender := common.HexToAddress(args.Sender)
	// sender and contract address are passed as hex strings
	codeb := self.xeth.CodeAtBytes(args.Address)
	codeHash := common.BytesToHash(crypto.Sha3(codeb))
	contentHash := common.HexToHash(args.ContentHashHex)
	registry := registrar.New(self.xeth)

	_, err := registry.SetHashToHash(sender, codeHash, contentHash)
	if err != nil {
		return false, err
	}

	return true, nil
}

func (self *adminApi) RegisterUrl(req *shared.Request) (interface{}, error) {
	args := new(RegisterUrlArgs)
	if err := self.coder.Decode(req.Params, &args); err != nil {
		return nil, shared.NewDecodeParamError(err.Error())
	}

	sender := common.HexToAddress(args.Sender)
	registry := registrar.New(self.xeth)
	_, err := registry.SetUrlToHash(sender, common.HexToHash(args.ContentHash), args.Url)
	if err != nil {
		return false, err
	}

	return true, nil
}

func (self *adminApi) StartNatSpec(req *shared.Request) (interface{}, error) {
	self.ethereum.NatSpec = true
	return true, nil
}

func (self *adminApi) StopNatSpec(req *shared.Request) (interface{}, error) {
	self.ethereum.NatSpec = false
	return true, nil
}

func (self *adminApi) GetContractInfo(req *shared.Request) (interface{}, error) {
	args := new(GetContractInfoArgs)
	if err := self.coder.Decode(req.Params, &args); err != nil {
		return nil, shared.NewDecodeParamError(err.Error())
	}

Z
zelig 已提交
440
	infoDoc, err := natspec.FetchDocsForContract(args.Contract, self.xeth, self.ethereum.HTTPClient())
Z
zelig 已提交
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
	if err != nil {
		return nil, err
	}

	var info interface{}
	err = self.coder.Decode(infoDoc, &info)
	if err != nil {
		return nil, err
	}

	return info, nil
}

func (self *adminApi) HttpGet(req *shared.Request) (interface{}, error) {
	args := new(HttpGetArgs)
	if err := self.coder.Decode(req.Params, &args); err != nil {
		return nil, shared.NewDecodeParamError(err.Error())
	}

Z
zelig 已提交
460
	resp, err := self.ethereum.HTTPClient().Get(args.Uri, args.Path)
Z
zelig 已提交
461 462 463 464 465 466
	if err != nil {
		return nil, err
	}

	return string(resp), nil
}
B
Bas van Kervel 已提交
467 468 469 470 471 472 473

func (self *adminApi) EnableUserAgent(req *shared.Request) (interface{}, error) {
	if fe, ok := self.xeth.Frontend().(*useragent.RemoteFrontend); ok {
		fe.Enable()
	}
	return true, nil
}