github.com/ur-technology/go-ur@v1.5.5/internal/ethapi/api.go (about) 1 // Copyright 2015 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // 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/>. 16 17 package ethapi 18 19 import ( 20 "bytes" 21 "encoding/hex" 22 "encoding/json" 23 "fmt" 24 "math/big" 25 "strings" 26 "time" 27 28 "github.com/ethereum/ethash" 29 "github.com/ethereum/go-ethereum/accounts" 30 "github.com/ethereum/go-ethereum/common" 31 "github.com/ethereum/go-ethereum/core" 32 "github.com/ethereum/go-ethereum/core/types" 33 "github.com/ethereum/go-ethereum/core/vm" 34 "github.com/ethereum/go-ethereum/crypto" 35 "github.com/ethereum/go-ethereum/ethdb" 36 "github.com/ethereum/go-ethereum/logger" 37 "github.com/ethereum/go-ethereum/logger/glog" 38 "github.com/ethereum/go-ethereum/p2p" 39 "github.com/ethereum/go-ethereum/rlp" 40 "github.com/ethereum/go-ethereum/rpc" 41 "github.com/syndtr/goleveldb/leveldb" 42 "github.com/syndtr/goleveldb/leveldb/util" 43 "golang.org/x/net/context" 44 ) 45 46 const defaultGas = uint64(90000) 47 48 // PublicEthereumAPI provides an API to access Ethereum related information. 49 // It offers only methods that operate on public data that is freely available to anyone. 50 type PublicEthereumAPI struct { 51 b Backend 52 } 53 54 // NewPublicEthereumAPI creates a new Etheruem protocol API. 55 func NewPublicEthereumAPI(b Backend) *PublicEthereumAPI { 56 return &PublicEthereumAPI{b} 57 } 58 59 // GasPrice returns a suggestion for a gas price. 60 func (s *PublicEthereumAPI) GasPrice(ctx context.Context) (*big.Int, error) { 61 return s.b.SuggestPrice(ctx) 62 } 63 64 // ProtocolVersion returns the current Ethereum protocol version this node supports 65 func (s *PublicEthereumAPI) ProtocolVersion() *rpc.HexNumber { 66 return rpc.NewHexNumber(s.b.ProtocolVersion()) 67 } 68 69 // Syncing returns false in case the node is currently not syncing with the network. It can be up to date or has not 70 // yet received the latest block headers from its pears. In case it is synchronizing: 71 // - startingBlock: block number this node started to synchronise from 72 // - currentBlock: block number this node is currently importing 73 // - highestBlock: block number of the highest block header this node has received from peers 74 // - pulledStates: number of state entries processed until now 75 // - knownStates: number of known state entries that still need to be pulled 76 func (s *PublicEthereumAPI) Syncing() (interface{}, error) { 77 progress := s.b.Downloader().Progress() 78 79 // Return not syncing if the synchronisation already completed 80 if progress.CurrentBlock >= progress.HighestBlock { 81 return false, nil 82 } 83 // Otherwise gather the block sync stats 84 return map[string]interface{}{ 85 "startingBlock": rpc.NewHexNumber(progress.StartingBlock), 86 "currentBlock": rpc.NewHexNumber(progress.CurrentBlock), 87 "highestBlock": rpc.NewHexNumber(progress.HighestBlock), 88 "pulledStates": rpc.NewHexNumber(progress.PulledStates), 89 "knownStates": rpc.NewHexNumber(progress.KnownStates), 90 }, nil 91 } 92 93 // PublicTxPoolAPI offers and API for the transaction pool. It only operates on data that is non confidential. 94 type PublicTxPoolAPI struct { 95 b Backend 96 } 97 98 // NewPublicTxPoolAPI creates a new tx pool service that gives information about the transaction pool. 99 func NewPublicTxPoolAPI(b Backend) *PublicTxPoolAPI { 100 return &PublicTxPoolAPI{b} 101 } 102 103 // Content returns the transactions contained within the transaction pool. 104 func (s *PublicTxPoolAPI) Content() map[string]map[string]map[string]*RPCTransaction { 105 content := map[string]map[string]map[string]*RPCTransaction{ 106 "pending": make(map[string]map[string]*RPCTransaction), 107 "queued": make(map[string]map[string]*RPCTransaction), 108 } 109 pending, queue := s.b.TxPoolContent() 110 111 // Flatten the pending transactions 112 for account, txs := range pending { 113 dump := make(map[string]*RPCTransaction) 114 for nonce, tx := range txs { 115 dump[fmt.Sprintf("%d", nonce)] = newRPCPendingTransaction(tx) 116 } 117 content["pending"][account.Hex()] = dump 118 } 119 // Flatten the queued transactions 120 for account, txs := range queue { 121 dump := make(map[string]*RPCTransaction) 122 for nonce, tx := range txs { 123 dump[fmt.Sprintf("%d", nonce)] = newRPCPendingTransaction(tx) 124 } 125 content["queued"][account.Hex()] = dump 126 } 127 return content 128 } 129 130 // Status returns the number of pending and queued transaction in the pool. 131 func (s *PublicTxPoolAPI) Status() map[string]*rpc.HexNumber { 132 pending, queue := s.b.Stats() 133 return map[string]*rpc.HexNumber{ 134 "pending": rpc.NewHexNumber(pending), 135 "queued": rpc.NewHexNumber(queue), 136 } 137 } 138 139 // Inspect retrieves the content of the transaction pool and flattens it into an 140 // easily inspectable list. 141 func (s *PublicTxPoolAPI) Inspect() map[string]map[string]map[string]string { 142 content := map[string]map[string]map[string]string{ 143 "pending": make(map[string]map[string]string), 144 "queued": make(map[string]map[string]string), 145 } 146 pending, queue := s.b.TxPoolContent() 147 148 // Define a formatter to flatten a transaction into a string 149 var format = func(tx *types.Transaction) string { 150 if to := tx.To(); to != nil { 151 return fmt.Sprintf("%s: %v wei + %v × %v gas", tx.To().Hex(), tx.Value(), tx.Gas(), tx.GasPrice()) 152 } 153 return fmt.Sprintf("contract creation: %v wei + %v × %v gas", tx.Value(), tx.Gas(), tx.GasPrice()) 154 } 155 // Flatten the pending transactions 156 for account, txs := range pending { 157 dump := make(map[string]string) 158 for nonce, tx := range txs { 159 dump[fmt.Sprintf("%d", nonce)] = format(tx) 160 } 161 content["pending"][account.Hex()] = dump 162 } 163 // Flatten the queued transactions 164 for account, txs := range queue { 165 dump := make(map[string]string) 166 for nonce, tx := range txs { 167 dump[fmt.Sprintf("%d", nonce)] = format(tx) 168 } 169 content["queued"][account.Hex()] = dump 170 } 171 return content 172 } 173 174 // PublicAccountAPI provides an API to access accounts managed by this node. 175 // It offers only methods that can retrieve accounts. 176 type PublicAccountAPI struct { 177 am *accounts.Manager 178 } 179 180 // NewPublicAccountAPI creates a new PublicAccountAPI. 181 func NewPublicAccountAPI(am *accounts.Manager) *PublicAccountAPI { 182 return &PublicAccountAPI{am: am} 183 } 184 185 // Accounts returns the collection of accounts this node manages 186 func (s *PublicAccountAPI) Accounts() []accounts.Account { 187 return s.am.Accounts() 188 } 189 190 // PrivateAccountAPI provides an API to access accounts managed by this node. 191 // It offers methods to create, (un)lock en list accounts. Some methods accept 192 // passwords and are therefore considered private by default. 193 type PrivateAccountAPI struct { 194 am *accounts.Manager 195 b Backend 196 } 197 198 // NewPrivateAccountAPI create a new PrivateAccountAPI. 199 func NewPrivateAccountAPI(b Backend) *PrivateAccountAPI { 200 return &PrivateAccountAPI{ 201 am: b.AccountManager(), 202 b: b, 203 } 204 } 205 206 // ListAccounts will return a list of addresses for accounts this node manages. 207 func (s *PrivateAccountAPI) ListAccounts() []common.Address { 208 accounts := s.am.Accounts() 209 addresses := make([]common.Address, len(accounts)) 210 for i, acc := range accounts { 211 addresses[i] = acc.Address 212 } 213 return addresses 214 } 215 216 // NewAccount will create a new account and returns the address for the new account. 217 func (s *PrivateAccountAPI) NewAccount(password string) (common.Address, error) { 218 acc, err := s.am.NewAccount(password) 219 if err == nil { 220 return acc.Address, nil 221 } 222 return common.Address{}, err 223 } 224 225 // ImportRawKey stores the given hex encoded ECDSA key into the key directory, 226 // encrypting it with the passphrase. 227 func (s *PrivateAccountAPI) ImportRawKey(privkey string, password string) (common.Address, error) { 228 hexkey, err := hex.DecodeString(privkey) 229 if err != nil { 230 return common.Address{}, err 231 } 232 233 acc, err := s.am.ImportECDSA(crypto.ToECDSA(hexkey), password) 234 return acc.Address, err 235 } 236 237 // UnlockAccount will unlock the account associated with the given address with 238 // the given password for duration seconds. If duration is nil it will use a 239 // default of 300 seconds. It returns an indication if the account was unlocked. 240 func (s *PrivateAccountAPI) UnlockAccount(addr common.Address, password string, duration *rpc.HexNumber) (bool, error) { 241 if duration == nil { 242 duration = rpc.NewHexNumber(300) 243 } 244 a := accounts.Account{Address: addr} 245 d := time.Duration(duration.Int64()) * time.Second 246 if err := s.am.TimedUnlock(a, password, d); err != nil { 247 return false, err 248 } 249 return true, nil 250 } 251 252 // LockAccount will lock the account associated with the given address when it's unlocked. 253 func (s *PrivateAccountAPI) LockAccount(addr common.Address) bool { 254 return s.am.Lock(addr) == nil 255 } 256 257 // SendTransaction will create a transaction from the given arguments and 258 // tries to sign it with the key associated with args.To. If the given passwd isn't 259 // able to decrypt the key it fails. 260 func (s *PrivateAccountAPI) SendTransaction(ctx context.Context, args SendTxArgs, passwd string) (common.Hash, error) { 261 var err error 262 args, err = prepareSendTxArgs(ctx, args, s.b) 263 if err != nil { 264 return common.Hash{}, err 265 } 266 267 if args.Nonce == nil { 268 nonce, err := s.b.GetPoolNonce(ctx, args.From) 269 if err != nil { 270 return common.Hash{}, err 271 } 272 args.Nonce = rpc.NewHexNumber(nonce) 273 } 274 275 var tx *types.Transaction 276 if args.To == nil { 277 tx = types.NewContractCreation(args.Nonce.Uint64(), args.Value.BigInt(), args.Gas.BigInt(), args.GasPrice.BigInt(), common.FromHex(args.Data)) 278 } else { 279 tx = types.NewTransaction(args.Nonce.Uint64(), *args.To, args.Value.BigInt(), args.Gas.BigInt(), args.GasPrice.BigInt(), common.FromHex(args.Data)) 280 } 281 282 signer := types.MakeSigner(s.b.ChainConfig(), s.b.CurrentBlock().Number()) 283 signature, err := s.am.SignWithPassphrase(args.From, passwd, signer.Hash(tx).Bytes()) 284 if err != nil { 285 return common.Hash{}, err 286 } 287 288 return submitTransaction(ctx, s.b, tx, signature) 289 } 290 291 // signHash is a helper function that calculates a hash for the given message that can be 292 // safely used to calculate a signature from. The hash is calulcated with: 293 // keccak256("\x19Ethereum Signed Message:\n"${message length}${message}). 294 func signHash(message string) []byte { 295 data := common.FromHex(message) 296 // Give context to the signed message. This prevents an adversery to sign a tx. 297 // It has no cryptographic purpose. 298 msg := fmt.Sprintf("\x19Ethereum Signed Message:\n%d%s", len(data), data) 299 // Always hash, this prevents choosen plaintext attacks that can extract key information 300 return crypto.Keccak256([]byte(msg)) 301 } 302 303 // Sign calculates an Ethereum ECDSA signature for: 304 // keccack256("\x19Ethereum Signed Message:\n" + len(message) + message)) 305 // 306 // The key used to calculate the signature is decrypted with the given password. 307 // 308 // https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_sign 309 func (s *PrivateAccountAPI) Sign(ctx context.Context, message string, addr common.Address, passwd string) (string, error) { 310 hash := signHash(message) 311 signature, err := s.b.AccountManager().SignWithPassphrase(addr, passwd, hash) 312 if err != nil { 313 return "0x", err 314 } 315 return common.ToHex(signature), nil 316 } 317 318 // EcRecover returns the address for the account that was used to create the signature. 319 // Note, this function is compatible with eth_sign and personal_sign. As such it recovers 320 // the address of: 321 // hash = keccak256("\x19Ethereum Signed Message:\n"${message length}${message}) 322 // addr = ecrecover(hash, signature) 323 // 324 // https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_ecRecover 325 func (s *PrivateAccountAPI) EcRecover(ctx context.Context, message string, signature string) (common.Address, error) { 326 var ( 327 hash = signHash(message) 328 sig = common.FromHex(signature) 329 ) 330 331 if len(sig) != 65 { 332 return common.Address{}, fmt.Errorf("signature must be 65 bytes long") 333 } 334 335 // see crypto.Ecrecover description 336 if sig[64] == 27 || sig[64] == 28 { 337 sig[64] -= 27 338 } 339 340 rpk, err := crypto.Ecrecover(hash, sig) 341 if err != nil { 342 return common.Address{}, err 343 } 344 345 pubKey := crypto.ToECDSAPub(rpk) 346 recoveredAddr := crypto.PubkeyToAddress(*pubKey) 347 348 return recoveredAddr, nil 349 } 350 351 // SignAndSendTransaction was renamed to SendTransaction. This method is deprecated 352 // and will be removed in the future. It primary goal is to give clients time to update. 353 func (s *PrivateAccountAPI) SignAndSendTransaction(ctx context.Context, args SendTxArgs, passwd string) (common.Hash, error) { 354 return s.SendTransaction(ctx, args, passwd) 355 } 356 357 // PublicBlockChainAPI provides an API to access the Ethereum blockchain. 358 // It offers only methods that operate on public data that is freely available to anyone. 359 type PublicBlockChainAPI struct { 360 b Backend 361 } 362 363 // NewPublicBlockChainAPI creates a new Etheruem blockchain API. 364 func NewPublicBlockChainAPI(b Backend) *PublicBlockChainAPI { 365 return &PublicBlockChainAPI{b} 366 } 367 368 // BlockNumber returns the block number of the chain head. 369 func (s *PublicBlockChainAPI) BlockNumber() *big.Int { 370 header, _ := s.b.HeaderByNumber(context.Background(), rpc.LatestBlockNumber) // latest header should always be available 371 return header.Number 372 } 373 374 // GetBalance returns the amount of wei for the given address in the state of the 375 // given block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta 376 // block numbers are also allowed. 377 func (s *PublicBlockChainAPI) GetBalance(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (*big.Int, error) { 378 state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr) 379 if state == nil || err != nil { 380 return nil, err 381 } 382 383 return state.GetBalance(ctx, address) 384 } 385 386 // GetBlockByNumber returns the requested block. When blockNr is -1 the chain head is returned. When fullTx is true all 387 // transactions in the block are returned in full detail, otherwise only the transaction hash is returned. 388 func (s *PublicBlockChainAPI) GetBlockByNumber(ctx context.Context, blockNr rpc.BlockNumber, fullTx bool) (map[string]interface{}, error) { 389 block, err := s.b.BlockByNumber(ctx, blockNr) 390 if block != nil { 391 response, err := s.rpcOutputBlock(block, true, fullTx) 392 if err == nil && blockNr == rpc.PendingBlockNumber { 393 // Pending blocks need to nil out a few fields 394 for _, field := range []string{"hash", "nonce", "logsBloom", "miner"} { 395 response[field] = nil 396 } 397 } 398 return response, err 399 } 400 return nil, err 401 } 402 403 // GetBlockByHash returns the requested block. When fullTx is true all transactions in the block are returned in full 404 // detail, otherwise only the transaction hash is returned. 405 func (s *PublicBlockChainAPI) GetBlockByHash(ctx context.Context, blockHash common.Hash, fullTx bool) (map[string]interface{}, error) { 406 block, err := s.b.GetBlock(ctx, blockHash) 407 if block != nil { 408 return s.rpcOutputBlock(block, true, fullTx) 409 } 410 return nil, err 411 } 412 413 // GetUncleByBlockNumberAndIndex returns the uncle block for the given block hash and index. When fullTx is true 414 // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned. 415 func (s *PublicBlockChainAPI) GetUncleByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index rpc.HexNumber) (map[string]interface{}, error) { 416 block, err := s.b.BlockByNumber(ctx, blockNr) 417 if block != nil { 418 uncles := block.Uncles() 419 if index.Int() < 0 || index.Int() >= len(uncles) { 420 glog.V(logger.Debug).Infof("uncle block on index %d not found for block #%d", index.Int(), blockNr) 421 return nil, nil 422 } 423 block = types.NewBlockWithHeader(uncles[index.Int()]) 424 return s.rpcOutputBlock(block, false, false) 425 } 426 return nil, err 427 } 428 429 // GetUncleByBlockHashAndIndex returns the uncle block for the given block hash and index. When fullTx is true 430 // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned. 431 func (s *PublicBlockChainAPI) GetUncleByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index rpc.HexNumber) (map[string]interface{}, error) { 432 block, err := s.b.GetBlock(ctx, blockHash) 433 if block != nil { 434 uncles := block.Uncles() 435 if index.Int() < 0 || index.Int() >= len(uncles) { 436 glog.V(logger.Debug).Infof("uncle block on index %d not found for block %s", index.Int(), blockHash.Hex()) 437 return nil, nil 438 } 439 block = types.NewBlockWithHeader(uncles[index.Int()]) 440 return s.rpcOutputBlock(block, false, false) 441 } 442 return nil, err 443 } 444 445 // GetUncleCountByBlockNumber returns number of uncles in the block for the given block number 446 func (s *PublicBlockChainAPI) GetUncleCountByBlockNumber(ctx context.Context, blockNr rpc.BlockNumber) *rpc.HexNumber { 447 if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil { 448 return rpc.NewHexNumber(len(block.Uncles())) 449 } 450 return nil 451 } 452 453 // GetUncleCountByBlockHash returns number of uncles in the block for the given block hash 454 func (s *PublicBlockChainAPI) GetUncleCountByBlockHash(ctx context.Context, blockHash common.Hash) *rpc.HexNumber { 455 if block, _ := s.b.GetBlock(ctx, blockHash); block != nil { 456 return rpc.NewHexNumber(len(block.Uncles())) 457 } 458 return nil 459 } 460 461 // GetCode returns the code stored at the given address in the state for the given block number. 462 func (s *PublicBlockChainAPI) GetCode(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (string, error) { 463 state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr) 464 if state == nil || err != nil { 465 return "", err 466 } 467 res, err := state.GetCode(ctx, address) 468 if len(res) == 0 || err != nil { // backwards compatibility 469 return "0x", err 470 } 471 return common.ToHex(res), nil 472 } 473 474 // GetStorageAt returns the storage from the state at the given address, key and 475 // block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta block 476 // numbers are also allowed. 477 func (s *PublicBlockChainAPI) GetStorageAt(ctx context.Context, address common.Address, key string, blockNr rpc.BlockNumber) (string, error) { 478 state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr) 479 if state == nil || err != nil { 480 return "0x", err 481 } 482 res, err := state.GetState(ctx, address, common.HexToHash(key)) 483 if err != nil { 484 return "0x", err 485 } 486 return res.Hex(), nil 487 } 488 489 // callmsg is the message type used for call transations. 490 type callmsg struct { 491 addr common.Address 492 to *common.Address 493 gas, gasPrice *big.Int 494 value *big.Int 495 data []byte 496 } 497 498 // accessor boilerplate to implement core.Message 499 func (m callmsg) From() (common.Address, error) { return m.addr, nil } 500 func (m callmsg) FromFrontier() (common.Address, error) { return m.addr, nil } 501 func (m callmsg) Nonce() uint64 { return 0 } 502 func (m callmsg) CheckNonce() bool { return false } 503 func (m callmsg) To() *common.Address { return m.to } 504 func (m callmsg) GasPrice() *big.Int { return m.gasPrice } 505 func (m callmsg) Gas() *big.Int { return m.gas } 506 func (m callmsg) Value() *big.Int { return m.value } 507 func (m callmsg) Data() []byte { return m.data } 508 509 // CallArgs represents the arguments for a call. 510 type CallArgs struct { 511 From common.Address `json:"from"` 512 To *common.Address `json:"to"` 513 Gas rpc.HexNumber `json:"gas"` 514 GasPrice rpc.HexNumber `json:"gasPrice"` 515 Value rpc.HexNumber `json:"value"` 516 Data string `json:"data"` 517 } 518 519 func (s *PublicBlockChainAPI) doCall(ctx context.Context, args CallArgs, blockNr rpc.BlockNumber) (string, *big.Int, error) { 520 defer func(start time.Time) { glog.V(logger.Debug).Infof("call took %v", time.Since(start)) }(time.Now()) 521 522 state, header, err := s.b.StateAndHeaderByNumber(ctx, blockNr) 523 if state == nil || err != nil { 524 return "0x", common.Big0, err 525 } 526 527 // Set the account address to interact with 528 var addr common.Address 529 if args.From == (common.Address{}) { 530 accounts := s.b.AccountManager().Accounts() 531 if len(accounts) == 0 { 532 addr = common.Address{} 533 } else { 534 addr = accounts[0].Address 535 } 536 } else { 537 addr = args.From 538 } 539 540 // Assemble the CALL invocation 541 gas, gasPrice := args.Gas.BigInt(), args.GasPrice.BigInt() 542 if gas.Cmp(common.Big0) == 0 { 543 gas = big.NewInt(50000000) 544 } 545 if gasPrice.Cmp(common.Big0) == 0 { 546 gasPrice = new(big.Int).Mul(big.NewInt(50), common.Shannon) 547 } 548 msg := types.NewMessage(addr, args.To, 0, args.Value.BigInt(), gas, gasPrice, common.FromHex(args.Data), false) 549 550 // Execute the call and return 551 vmenv, vmError, err := s.b.GetVMEnv(ctx, msg, state, header) 552 if err != nil { 553 return "0x", common.Big0, err 554 } 555 gp := new(core.GasPool).AddGas(common.MaxBig) 556 res, gas, err := core.ApplyMessage(vmenv, msg, gp) 557 if err := vmError(); err != nil { 558 return "0x", common.Big0, err 559 } 560 if len(res) == 0 { // backwards compatability 561 return "0x", gas, err 562 } 563 return common.ToHex(res), gas, err 564 } 565 566 // Call executes the given transaction on the state for the given block number. 567 // It doesn't make and changes in the state/blockchain and is usefull to execute and retrieve values. 568 func (s *PublicBlockChainAPI) Call(ctx context.Context, args CallArgs, blockNr rpc.BlockNumber) (string, error) { 569 result, _, err := s.doCall(ctx, args, blockNr) 570 return result, err 571 } 572 573 // EstimateGas returns an estimate of the amount of gas needed to execute the given transaction. 574 func (s *PublicBlockChainAPI) EstimateGas(ctx context.Context, args CallArgs) (*rpc.HexNumber, error) { 575 _, gas, err := s.doCall(ctx, args, rpc.PendingBlockNumber) 576 return rpc.NewHexNumber(gas), err 577 } 578 579 // ExecutionResult groups all structured logs emitted by the EVM 580 // while replaying a transaction in debug mode as well as the amount of 581 // gas used and the return value 582 type ExecutionResult struct { 583 Gas *big.Int `json:"gas"` 584 ReturnValue string `json:"returnValue"` 585 StructLogs []StructLogRes `json:"structLogs"` 586 } 587 588 // StructLogRes stores a structured log emitted by the EVM while replaying a 589 // transaction in debug mode 590 type StructLogRes struct { 591 Pc uint64 `json:"pc"` 592 Op string `json:"op"` 593 Gas *big.Int `json:"gas"` 594 GasCost *big.Int `json:"gasCost"` 595 Depth int `json:"depth"` 596 Error error `json:"error"` 597 Stack []string `json:"stack"` 598 Memory []string `json:"memory"` 599 Storage map[string]string `json:"storage"` 600 } 601 602 // formatLogs formats EVM returned structured logs for json output 603 func FormatLogs(structLogs []vm.StructLog) []StructLogRes { 604 formattedStructLogs := make([]StructLogRes, len(structLogs)) 605 for index, trace := range structLogs { 606 formattedStructLogs[index] = StructLogRes{ 607 Pc: trace.Pc, 608 Op: trace.Op.String(), 609 Gas: trace.Gas, 610 GasCost: trace.GasCost, 611 Depth: trace.Depth, 612 Error: trace.Err, 613 Stack: make([]string, len(trace.Stack)), 614 Storage: make(map[string]string), 615 } 616 617 for i, stackValue := range trace.Stack { 618 formattedStructLogs[index].Stack[i] = fmt.Sprintf("%x", common.LeftPadBytes(stackValue.Bytes(), 32)) 619 } 620 621 for i := 0; i+32 <= len(trace.Memory); i += 32 { 622 formattedStructLogs[index].Memory = append(formattedStructLogs[index].Memory, fmt.Sprintf("%x", trace.Memory[i:i+32])) 623 } 624 625 for i, storageValue := range trace.Storage { 626 formattedStructLogs[index].Storage[fmt.Sprintf("%x", i)] = fmt.Sprintf("%x", storageValue) 627 } 628 } 629 return formattedStructLogs 630 } 631 632 // rpcOutputBlock converts the given block to the RPC output which depends on fullTx. If inclTx is true transactions are 633 // returned. When fullTx is true the returned block contains full transaction details, otherwise it will only contain 634 // transaction hashes. 635 func (s *PublicBlockChainAPI) rpcOutputBlock(b *types.Block, inclTx bool, fullTx bool) (map[string]interface{}, error) { 636 head := b.Header() // copies the header once 637 fields := map[string]interface{}{ 638 "number": rpc.NewHexNumber(head.Number), 639 "hash": b.Hash(), 640 "parentHash": head.ParentHash, 641 "nonce": head.Nonce, 642 "mixHash": head.MixDigest, 643 "sha3Uncles": head.UncleHash, 644 "logsBloom": head.Bloom, 645 "stateRoot": head.Root, 646 "miner": head.Coinbase, 647 "difficulty": rpc.NewHexNumber(head.Difficulty), 648 "totalDifficulty": rpc.NewHexNumber(s.b.GetTd(b.Hash())), 649 "extraData": rpc.HexBytes(head.Extra), 650 "size": rpc.NewHexNumber(b.Size().Int64()), 651 "gasLimit": rpc.NewHexNumber(head.GasLimit), 652 "gasUsed": rpc.NewHexNumber(head.GasUsed), 653 "timestamp": rpc.NewHexNumber(head.Time), 654 "transactionsRoot": head.TxHash, 655 "receiptsRoot": head.ReceiptHash, 656 } 657 658 if inclTx { 659 formatTx := func(tx *types.Transaction) (interface{}, error) { 660 return tx.Hash(), nil 661 } 662 663 if fullTx { 664 formatTx = func(tx *types.Transaction) (interface{}, error) { 665 return newRPCTransaction(b, tx.Hash()) 666 } 667 } 668 669 txs := b.Transactions() 670 transactions := make([]interface{}, len(txs)) 671 var err error 672 for i, tx := range b.Transactions() { 673 if transactions[i], err = formatTx(tx); err != nil { 674 return nil, err 675 } 676 } 677 fields["transactions"] = transactions 678 } 679 680 uncles := b.Uncles() 681 uncleHashes := make([]common.Hash, len(uncles)) 682 for i, uncle := range uncles { 683 uncleHashes[i] = uncle.Hash() 684 } 685 fields["uncles"] = uncleHashes 686 687 return fields, nil 688 } 689 690 // RPCTransaction represents a transaction that will serialize to the RPC representation of a transaction 691 type RPCTransaction struct { 692 BlockHash common.Hash `json:"blockHash"` 693 BlockNumber *rpc.HexNumber `json:"blockNumber"` 694 From common.Address `json:"from"` 695 Gas *rpc.HexNumber `json:"gas"` 696 GasPrice *rpc.HexNumber `json:"gasPrice"` 697 Hash common.Hash `json:"hash"` 698 Input rpc.HexBytes `json:"input"` 699 Nonce *rpc.HexNumber `json:"nonce"` 700 To *common.Address `json:"to"` 701 TransactionIndex *rpc.HexNumber `json:"transactionIndex"` 702 Value *rpc.HexNumber `json:"value"` 703 V *rpc.HexNumber `json:"v"` 704 R *rpc.HexNumber `json:"r"` 705 S *rpc.HexNumber `json:"s"` 706 } 707 708 // newRPCPendingTransaction returns a pending transaction that will serialize to the RPC representation 709 func newRPCPendingTransaction(tx *types.Transaction) *RPCTransaction { 710 var signer types.Signer = types.FrontierSigner{} 711 if tx.Protected() { 712 signer = types.NewEIP155Signer(tx.ChainId()) 713 } 714 from, _ := types.Sender(signer, tx) 715 v, r, s := types.SignatureValues(signer, tx) 716 return &RPCTransaction{ 717 From: from, 718 Gas: rpc.NewHexNumber(tx.Gas()), 719 GasPrice: rpc.NewHexNumber(tx.GasPrice()), 720 Hash: tx.Hash(), 721 Input: rpc.HexBytes(tx.Data()), 722 Nonce: rpc.NewHexNumber(tx.Nonce()), 723 To: tx.To(), 724 Value: rpc.NewHexNumber(tx.Value()), 725 V: rpc.NewHexNumber(v), 726 R: rpc.NewHexNumber(r), 727 S: rpc.NewHexNumber(s), 728 } 729 } 730 731 // newRPCTransaction returns a transaction that will serialize to the RPC representation. 732 func newRPCTransactionFromBlockIndex(b *types.Block, txIndex int) (*RPCTransaction, error) { 733 if txIndex >= 0 && txIndex < len(b.Transactions()) { 734 tx := b.Transactions()[txIndex] 735 var signer types.Signer = types.FrontierSigner{} 736 if tx.Protected() { 737 signer = types.NewEIP155Signer(tx.ChainId()) 738 } 739 from, _ := types.Sender(signer, tx) 740 v, r, s := tx.RawSignatureValues() 741 return &RPCTransaction{ 742 BlockHash: b.Hash(), 743 BlockNumber: rpc.NewHexNumber(b.Number()), 744 From: from, 745 Gas: rpc.NewHexNumber(tx.Gas()), 746 GasPrice: rpc.NewHexNumber(tx.GasPrice()), 747 Hash: tx.Hash(), 748 Input: rpc.HexBytes(tx.Data()), 749 Nonce: rpc.NewHexNumber(tx.Nonce()), 750 To: tx.To(), 751 TransactionIndex: rpc.NewHexNumber(txIndex), 752 Value: rpc.NewHexNumber(tx.Value()), 753 V: rpc.NewHexNumber(v), 754 R: rpc.NewHexNumber(r), 755 S: rpc.NewHexNumber(s), 756 }, nil 757 } 758 759 return nil, nil 760 } 761 762 // newRPCRawTransactionFromBlockIndex returns the bytes of a transaction given a block and a transaction index. 763 func newRPCRawTransactionFromBlockIndex(b *types.Block, txIndex int) (rpc.HexBytes, error) { 764 if txIndex >= 0 && txIndex < len(b.Transactions()) { 765 tx := b.Transactions()[txIndex] 766 return rlp.EncodeToBytes(tx) 767 } 768 769 return nil, nil 770 } 771 772 // newRPCTransaction returns a transaction that will serialize to the RPC representation. 773 func newRPCTransaction(b *types.Block, txHash common.Hash) (*RPCTransaction, error) { 774 for idx, tx := range b.Transactions() { 775 if tx.Hash() == txHash { 776 return newRPCTransactionFromBlockIndex(b, idx) 777 } 778 } 779 780 return nil, nil 781 } 782 783 // PublicTransactionPoolAPI exposes methods for the RPC interface 784 type PublicTransactionPoolAPI struct { 785 b Backend 786 } 787 788 // NewPublicTransactionPoolAPI creates a new RPC service with methods specific for the transaction pool. 789 func NewPublicTransactionPoolAPI(b Backend) *PublicTransactionPoolAPI { 790 return &PublicTransactionPoolAPI{b} 791 } 792 793 func getTransaction(chainDb ethdb.Database, b Backend, txHash common.Hash) (*types.Transaction, bool, error) { 794 txData, err := chainDb.Get(txHash.Bytes()) 795 isPending := false 796 tx := new(types.Transaction) 797 798 if err == nil && len(txData) > 0 { 799 if err := rlp.DecodeBytes(txData, tx); err != nil { 800 return nil, isPending, err 801 } 802 } else { 803 // pending transaction? 804 tx = b.GetPoolTransaction(txHash) 805 isPending = true 806 } 807 808 return tx, isPending, nil 809 } 810 811 // GetBlockTransactionCountByNumber returns the number of transactions in the block with the given block number. 812 func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByNumber(ctx context.Context, blockNr rpc.BlockNumber) *rpc.HexNumber { 813 if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil { 814 return rpc.NewHexNumber(len(block.Transactions())) 815 } 816 return nil 817 } 818 819 // GetBlockTransactionCountByHash returns the number of transactions in the block with the given hash. 820 func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByHash(ctx context.Context, blockHash common.Hash) *rpc.HexNumber { 821 if block, _ := s.b.GetBlock(ctx, blockHash); block != nil { 822 return rpc.NewHexNumber(len(block.Transactions())) 823 } 824 return nil 825 } 826 827 // GetTransactionByBlockNumberAndIndex returns the transaction for the given block number and index. 828 func (s *PublicTransactionPoolAPI) GetTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index rpc.HexNumber) (*RPCTransaction, error) { 829 if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil { 830 return newRPCTransactionFromBlockIndex(block, index.Int()) 831 } 832 return nil, nil 833 } 834 835 // GetTransactionByBlockHashAndIndex returns the transaction for the given block hash and index. 836 func (s *PublicTransactionPoolAPI) GetTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index rpc.HexNumber) (*RPCTransaction, error) { 837 if block, _ := s.b.GetBlock(ctx, blockHash); block != nil { 838 return newRPCTransactionFromBlockIndex(block, index.Int()) 839 } 840 return nil, nil 841 } 842 843 // GetRawTransactionByBlockNumberAndIndex returns the bytes of the transaction for the given block number and index. 844 func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index rpc.HexNumber) (rpc.HexBytes, error) { 845 if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil { 846 return newRPCRawTransactionFromBlockIndex(block, index.Int()) 847 } 848 return nil, nil 849 } 850 851 // GetRawTransactionByBlockHashAndIndex returns the bytes of the transaction for the given block hash and index. 852 func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index rpc.HexNumber) (rpc.HexBytes, error) { 853 if block, _ := s.b.GetBlock(ctx, blockHash); block != nil { 854 return newRPCRawTransactionFromBlockIndex(block, index.Int()) 855 } 856 return nil, nil 857 } 858 859 // GetTransactionCount returns the number of transactions the given address has sent for the given block number 860 func (s *PublicTransactionPoolAPI) GetTransactionCount(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (*rpc.HexNumber, error) { 861 state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr) 862 if state == nil || err != nil { 863 return nil, err 864 } 865 nonce, err := state.GetNonce(ctx, address) 866 if err != nil { 867 return nil, err 868 } 869 return rpc.NewHexNumber(nonce), nil 870 } 871 872 // getTransactionBlockData fetches the meta data for the given transaction from the chain database. This is useful to 873 // retrieve block information for a hash. It returns the block hash, block index and transaction index. 874 func getTransactionBlockData(chainDb ethdb.Database, txHash common.Hash) (common.Hash, uint64, uint64, error) { 875 var txBlock struct { 876 BlockHash common.Hash 877 BlockIndex uint64 878 Index uint64 879 } 880 881 blockData, err := chainDb.Get(append(txHash.Bytes(), 0x0001)) 882 if err != nil { 883 return common.Hash{}, uint64(0), uint64(0), err 884 } 885 886 reader := bytes.NewReader(blockData) 887 if err = rlp.Decode(reader, &txBlock); err != nil { 888 return common.Hash{}, uint64(0), uint64(0), err 889 } 890 891 return txBlock.BlockHash, txBlock.BlockIndex, txBlock.Index, nil 892 } 893 894 // GetTransactionByHash returns the transaction for the given hash 895 func (s *PublicTransactionPoolAPI) GetTransactionByHash(ctx context.Context, txHash common.Hash) (*RPCTransaction, error) { 896 var tx *types.Transaction 897 var isPending bool 898 var err error 899 900 if tx, isPending, err = getTransaction(s.b.ChainDb(), s.b, txHash); err != nil { 901 glog.V(logger.Debug).Infof("%v\n", err) 902 return nil, nil 903 } else if tx == nil { 904 return nil, nil 905 } 906 907 if isPending { 908 return newRPCPendingTransaction(tx), nil 909 } 910 911 blockHash, _, _, err := getTransactionBlockData(s.b.ChainDb(), txHash) 912 if err != nil { 913 glog.V(logger.Debug).Infof("%v\n", err) 914 return nil, nil 915 } 916 917 if block, _ := s.b.GetBlock(ctx, blockHash); block != nil { 918 return newRPCTransaction(block, txHash) 919 } 920 921 return nil, nil 922 } 923 924 // GetRawTransactionByHash returns the bytes of the transaction for the given hash. 925 func (s *PublicTransactionPoolAPI) GetRawTransactionByHash(ctx context.Context, txHash common.Hash) (rpc.HexBytes, error) { 926 var tx *types.Transaction 927 var err error 928 929 if tx, _, err = getTransaction(s.b.ChainDb(), s.b, txHash); err != nil { 930 glog.V(logger.Debug).Infof("%v\n", err) 931 return nil, nil 932 } else if tx == nil { 933 return nil, nil 934 } 935 936 return rlp.EncodeToBytes(tx) 937 } 938 939 // GetTransactionReceipt returns the transaction receipt for the given transaction hash. 940 func (s *PublicTransactionPoolAPI) GetTransactionReceipt(txHash common.Hash) (map[string]interface{}, error) { 941 receipt := core.GetReceipt(s.b.ChainDb(), txHash) 942 if receipt == nil { 943 glog.V(logger.Debug).Infof("receipt not found for transaction %s", txHash.Hex()) 944 return nil, nil 945 } 946 947 tx, _, err := getTransaction(s.b.ChainDb(), s.b, txHash) 948 if err != nil { 949 glog.V(logger.Debug).Infof("%v\n", err) 950 return nil, nil 951 } 952 953 txBlock, blockIndex, index, err := getTransactionBlockData(s.b.ChainDb(), txHash) 954 if err != nil { 955 glog.V(logger.Debug).Infof("%v\n", err) 956 return nil, nil 957 } 958 959 var signer types.Signer = types.FrontierSigner{} 960 if tx.Protected() { 961 signer = types.NewEIP155Signer(tx.ChainId()) 962 } 963 from, _ := types.Sender(signer, tx) 964 965 fields := map[string]interface{}{ 966 "root": rpc.HexBytes(receipt.PostState), 967 "blockHash": txBlock, 968 "blockNumber": rpc.NewHexNumber(blockIndex), 969 "transactionHash": txHash, 970 "transactionIndex": rpc.NewHexNumber(index), 971 "from": from, 972 "to": tx.To(), 973 "gasUsed": rpc.NewHexNumber(receipt.GasUsed), 974 "cumulativeGasUsed": rpc.NewHexNumber(receipt.CumulativeGasUsed), 975 "contractAddress": nil, 976 "logs": receipt.Logs, 977 "logsBloom": receipt.Bloom, 978 } 979 if receipt.Logs == nil { 980 fields["logs"] = []vm.Logs{} 981 } 982 // If the ContractAddress is 20 0x0 bytes, assume it is not a contract creation 983 if receipt.ContractAddress != (common.Address{}) { 984 fields["contractAddress"] = receipt.ContractAddress 985 } 986 return fields, nil 987 } 988 989 // sign is a helper function that signs a transaction with the private key of the given address. 990 func (s *PublicTransactionPoolAPI) sign(addr common.Address, tx *types.Transaction) (*types.Transaction, error) { 991 signer := types.MakeSigner(s.b.ChainConfig(), s.b.CurrentBlock().Number()) 992 993 signature, err := s.b.AccountManager().SignEthereum(addr, signer.Hash(tx).Bytes()) 994 if err != nil { 995 return nil, err 996 } 997 return tx.WithSignature(signer, signature) 998 } 999 1000 // SendTxArgs represents the arguments to sumbit a new transaction into the transaction pool. 1001 type SendTxArgs struct { 1002 From common.Address `json:"from"` 1003 To *common.Address `json:"to"` 1004 Gas *rpc.HexNumber `json:"gas"` 1005 GasPrice *rpc.HexNumber `json:"gasPrice"` 1006 Value *rpc.HexNumber `json:"value"` 1007 Data string `json:"data"` 1008 Nonce *rpc.HexNumber `json:"nonce"` 1009 } 1010 1011 // prepareSendTxArgs is a helper function that fills in default values for unspecified tx fields. 1012 func prepareSendTxArgs(ctx context.Context, args SendTxArgs, b Backend) (SendTxArgs, error) { 1013 if args.Gas == nil { 1014 args.Gas = rpc.NewHexNumber(defaultGas) 1015 } 1016 if args.GasPrice == nil { 1017 price, err := b.SuggestPrice(ctx) 1018 if err != nil { 1019 return args, err 1020 } 1021 args.GasPrice = rpc.NewHexNumber(price) 1022 } 1023 if args.Value == nil { 1024 args.Value = rpc.NewHexNumber(0) 1025 } 1026 return args, nil 1027 } 1028 1029 // submitTransaction is a helper function that submits tx to txPool and creates a log entry. 1030 func submitTransaction(ctx context.Context, b Backend, tx *types.Transaction, signature []byte) (common.Hash, error) { 1031 signer := types.MakeSigner(b.ChainConfig(), b.CurrentBlock().Number()) 1032 1033 signedTx, err := tx.WithSignature(signer, signature) 1034 if err != nil { 1035 return common.Hash{}, err 1036 } 1037 1038 if err := b.SendTx(ctx, signedTx); err != nil { 1039 return common.Hash{}, err 1040 } 1041 1042 if signedTx.To() == nil { 1043 from, _ := types.Sender(signer, signedTx) 1044 addr := crypto.CreateAddress(from, signedTx.Nonce()) 1045 glog.V(logger.Info).Infof("Tx(%s) created: %s\n", signedTx.Hash().Hex(), addr.Hex()) 1046 } else { 1047 glog.V(logger.Info).Infof("Tx(%s) to: %s\n", signedTx.Hash().Hex(), tx.To().Hex()) 1048 } 1049 1050 return signedTx.Hash(), nil 1051 } 1052 1053 // SendTransaction creates a transaction for the given argument, sign it and submit it to the 1054 // transaction pool. 1055 func (s *PublicTransactionPoolAPI) SendTransaction(ctx context.Context, args SendTxArgs) (common.Hash, error) { 1056 var err error 1057 args, err = prepareSendTxArgs(ctx, args, s.b) 1058 if err != nil { 1059 return common.Hash{}, err 1060 } 1061 1062 if args.Nonce == nil { 1063 nonce, err := s.b.GetPoolNonce(ctx, args.From) 1064 if err != nil { 1065 return common.Hash{}, err 1066 } 1067 args.Nonce = rpc.NewHexNumber(nonce) 1068 } 1069 1070 var tx *types.Transaction 1071 if args.To == nil { 1072 tx = types.NewContractCreation(args.Nonce.Uint64(), args.Value.BigInt(), args.Gas.BigInt(), args.GasPrice.BigInt(), common.FromHex(args.Data)) 1073 } else { 1074 tx = types.NewTransaction(args.Nonce.Uint64(), *args.To, args.Value.BigInt(), args.Gas.BigInt(), args.GasPrice.BigInt(), common.FromHex(args.Data)) 1075 } 1076 1077 signer := types.MakeSigner(s.b.ChainConfig(), s.b.CurrentBlock().Number()) 1078 signature, err := s.b.AccountManager().SignEthereum(args.From, signer.Hash(tx).Bytes()) 1079 if err != nil { 1080 return common.Hash{}, err 1081 } 1082 1083 return submitTransaction(ctx, s.b, tx, signature) 1084 } 1085 1086 // SendRawTransaction will add the signed transaction to the transaction pool. 1087 // The sender is responsible for signing the transaction and using the correct nonce. 1088 func (s *PublicTransactionPoolAPI) SendRawTransaction(ctx context.Context, encodedTx string) (string, error) { 1089 tx := new(types.Transaction) 1090 if err := rlp.DecodeBytes(common.FromHex(encodedTx), tx); err != nil { 1091 return "", err 1092 } 1093 1094 if err := s.b.SendTx(ctx, tx); err != nil { 1095 return "", err 1096 } 1097 1098 signer := types.MakeSigner(s.b.ChainConfig(), s.b.CurrentBlock().Number()) 1099 if tx.To() == nil { 1100 from, err := types.Sender(signer, tx) 1101 if err != nil { 1102 return "", err 1103 } 1104 addr := crypto.CreateAddress(from, tx.Nonce()) 1105 glog.V(logger.Info).Infof("Tx(%x) created: %x\n", tx.Hash(), addr) 1106 } else { 1107 glog.V(logger.Info).Infof("Tx(%x) to: %x\n", tx.Hash(), tx.To()) 1108 } 1109 1110 return tx.Hash().Hex(), nil 1111 } 1112 1113 // Sign calculates an ECDSA signature for: 1114 // keccack256("\x19Ethereum Signed Message:\n" + len(message) + message). 1115 // 1116 // The account associated with addr must be unlocked. 1117 // 1118 // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign 1119 func (s *PublicTransactionPoolAPI) Sign(addr common.Address, message string) (string, error) { 1120 hash := signHash(message) 1121 signature, err := s.b.AccountManager().SignEthereum(addr, hash) 1122 return common.ToHex(signature), err 1123 } 1124 1125 // SignTransactionArgs represents the arguments to sign a transaction. 1126 type SignTransactionArgs struct { 1127 From common.Address 1128 To *common.Address 1129 Nonce *rpc.HexNumber 1130 Value *rpc.HexNumber 1131 Gas *rpc.HexNumber 1132 GasPrice *rpc.HexNumber 1133 Data string 1134 1135 BlockNumber int64 1136 } 1137 1138 // Tx is a helper object for argument and return values 1139 type Tx struct { 1140 tx *types.Transaction 1141 1142 To *common.Address `json:"to"` 1143 From common.Address `json:"from"` 1144 Nonce *rpc.HexNumber `json:"nonce"` 1145 Value *rpc.HexNumber `json:"value"` 1146 Data string `json:"data"` 1147 GasLimit *rpc.HexNumber `json:"gas"` 1148 GasPrice *rpc.HexNumber `json:"gasPrice"` 1149 Hash common.Hash `json:"hash"` 1150 } 1151 1152 // UnmarshalJSON parses JSON data into tx. 1153 func (tx *Tx) UnmarshalJSON(b []byte) (err error) { 1154 req := struct { 1155 To *common.Address `json:"to"` 1156 From common.Address `json:"from"` 1157 Nonce *rpc.HexNumber `json:"nonce"` 1158 Value *rpc.HexNumber `json:"value"` 1159 Data string `json:"data"` 1160 GasLimit *rpc.HexNumber `json:"gas"` 1161 GasPrice *rpc.HexNumber `json:"gasPrice"` 1162 Hash common.Hash `json:"hash"` 1163 }{} 1164 1165 if err := json.Unmarshal(b, &req); err != nil { 1166 return err 1167 } 1168 1169 tx.To = req.To 1170 tx.From = req.From 1171 tx.Nonce = req.Nonce 1172 tx.Value = req.Value 1173 tx.Data = req.Data 1174 tx.GasLimit = req.GasLimit 1175 tx.GasPrice = req.GasPrice 1176 tx.Hash = req.Hash 1177 1178 data := common.Hex2Bytes(tx.Data) 1179 1180 if tx.Nonce == nil { 1181 return fmt.Errorf("need nonce") 1182 } 1183 if tx.Value == nil { 1184 tx.Value = rpc.NewHexNumber(0) 1185 } 1186 if tx.GasLimit == nil { 1187 tx.GasLimit = rpc.NewHexNumber(0) 1188 } 1189 if tx.GasPrice == nil { 1190 tx.GasPrice = rpc.NewHexNumber(int64(50000000000)) 1191 } 1192 1193 if req.To == nil { 1194 tx.tx = types.NewContractCreation(tx.Nonce.Uint64(), tx.Value.BigInt(), tx.GasLimit.BigInt(), tx.GasPrice.BigInt(), data) 1195 } else { 1196 tx.tx = types.NewTransaction(tx.Nonce.Uint64(), *tx.To, tx.Value.BigInt(), tx.GasLimit.BigInt(), tx.GasPrice.BigInt(), data) 1197 } 1198 1199 return nil 1200 } 1201 1202 // SignTransactionResult represents a RLP encoded signed transaction. 1203 type SignTransactionResult struct { 1204 Raw string `json:"raw"` 1205 Tx *Tx `json:"tx"` 1206 } 1207 1208 func newTx(t *types.Transaction) *Tx { 1209 var signer types.Signer = types.HomesteadSigner{} 1210 if t.Protected() { 1211 signer = types.NewEIP155Signer(t.ChainId()) 1212 } 1213 1214 from, _ := types.Sender(signer, t) 1215 return &Tx{ 1216 tx: t, 1217 To: t.To(), 1218 From: from, 1219 Value: rpc.NewHexNumber(t.Value()), 1220 Nonce: rpc.NewHexNumber(t.Nonce()), 1221 Data: "0x" + common.Bytes2Hex(t.Data()), 1222 GasLimit: rpc.NewHexNumber(t.Gas()), 1223 GasPrice: rpc.NewHexNumber(t.GasPrice()), 1224 Hash: t.Hash(), 1225 } 1226 } 1227 1228 // SignTransaction will sign the given transaction with the from account. 1229 // The node needs to have the private key of the account corresponding with 1230 // the given from address and it needs to be unlocked. 1231 func (s *PublicTransactionPoolAPI) SignTransaction(ctx context.Context, args SignTransactionArgs) (*SignTransactionResult, error) { 1232 if args.Gas == nil { 1233 args.Gas = rpc.NewHexNumber(defaultGas) 1234 } 1235 if args.GasPrice == nil { 1236 price, err := s.b.SuggestPrice(ctx) 1237 if err != nil { 1238 return nil, err 1239 } 1240 args.GasPrice = rpc.NewHexNumber(price) 1241 } 1242 if args.Value == nil { 1243 args.Value = rpc.NewHexNumber(0) 1244 } 1245 1246 if args.Nonce == nil { 1247 nonce, err := s.b.GetPoolNonce(ctx, args.From) 1248 if err != nil { 1249 return nil, err 1250 } 1251 args.Nonce = rpc.NewHexNumber(nonce) 1252 } 1253 1254 var tx *types.Transaction 1255 if args.To == nil { 1256 tx = types.NewContractCreation(args.Nonce.Uint64(), args.Value.BigInt(), args.Gas.BigInt(), args.GasPrice.BigInt(), common.FromHex(args.Data)) 1257 } else { 1258 tx = types.NewTransaction(args.Nonce.Uint64(), *args.To, args.Value.BigInt(), args.Gas.BigInt(), args.GasPrice.BigInt(), common.FromHex(args.Data)) 1259 } 1260 1261 signedTx, err := s.sign(args.From, tx) 1262 if err != nil { 1263 return nil, err 1264 } 1265 1266 data, err := rlp.EncodeToBytes(signedTx) 1267 if err != nil { 1268 return nil, err 1269 } 1270 1271 return &SignTransactionResult{"0x" + common.Bytes2Hex(data), newTx(signedTx)}, nil 1272 } 1273 1274 // PendingTransactions returns the transactions that are in the transaction pool and have a from address that is one of 1275 // the accounts this node manages. 1276 func (s *PublicTransactionPoolAPI) PendingTransactions() ([]*RPCTransaction, error) { 1277 pending, err := s.b.GetPoolTransactions() 1278 if err != nil { 1279 return nil, err 1280 } 1281 1282 transactions := make([]*RPCTransaction, 0, len(pending)) 1283 for _, tx := range pending { 1284 var signer types.Signer = types.HomesteadSigner{} 1285 if tx.Protected() { 1286 signer = types.NewEIP155Signer(tx.ChainId()) 1287 } 1288 from, _ := types.Sender(signer, tx) 1289 if s.b.AccountManager().HasAddress(from) { 1290 transactions = append(transactions, newRPCPendingTransaction(tx)) 1291 } 1292 } 1293 return transactions, nil 1294 } 1295 1296 // Resend accepts an existing transaction and a new gas price and limit. It will remove the given transaction from the 1297 // pool and reinsert it with the new gas price and limit. 1298 func (s *PublicTransactionPoolAPI) Resend(ctx context.Context, tx Tx, gasPrice, gasLimit *rpc.HexNumber) (common.Hash, error) { 1299 pending, err := s.b.GetPoolTransactions() 1300 if err != nil { 1301 return common.Hash{}, err 1302 } 1303 1304 for _, p := range pending { 1305 var signer types.Signer = types.HomesteadSigner{} 1306 if p.Protected() { 1307 signer = types.NewEIP155Signer(p.ChainId()) 1308 } 1309 1310 if pFrom, err := types.Sender(signer, p); err == nil && pFrom == tx.From && signer.Hash(p) == signer.Hash(tx.tx) { 1311 if gasPrice == nil { 1312 gasPrice = rpc.NewHexNumber(tx.tx.GasPrice()) 1313 } 1314 if gasLimit == nil { 1315 gasLimit = rpc.NewHexNumber(tx.tx.Gas()) 1316 } 1317 1318 var newTx *types.Transaction 1319 if tx.tx.To() == nil { 1320 newTx = types.NewContractCreation(tx.tx.Nonce(), tx.tx.Value(), gasLimit.BigInt(), gasPrice.BigInt(), tx.tx.Data()) 1321 } else { 1322 newTx = types.NewTransaction(tx.tx.Nonce(), *tx.tx.To(), tx.tx.Value(), gasLimit.BigInt(), gasPrice.BigInt(), tx.tx.Data()) 1323 } 1324 1325 signedTx, err := s.sign(tx.From, newTx) 1326 if err != nil { 1327 return common.Hash{}, err 1328 } 1329 1330 s.b.RemoveTx(tx.Hash) 1331 if err = s.b.SendTx(ctx, signedTx); err != nil { 1332 return common.Hash{}, err 1333 } 1334 1335 return signedTx.Hash(), nil 1336 } 1337 } 1338 1339 return common.Hash{}, fmt.Errorf("Transaction %#x not found", tx.Hash) 1340 } 1341 1342 // PublicDebugAPI is the collection of Etheruem APIs exposed over the public 1343 // debugging endpoint. 1344 type PublicDebugAPI struct { 1345 b Backend 1346 } 1347 1348 // NewPublicDebugAPI creates a new API definition for the public debug methods 1349 // of the Ethereum service. 1350 func NewPublicDebugAPI(b Backend) *PublicDebugAPI { 1351 return &PublicDebugAPI{b: b} 1352 } 1353 1354 // GetBlockRlp retrieves the RLP encoded for of a single block. 1355 func (api *PublicDebugAPI) GetBlockRlp(ctx context.Context, number uint64) (string, error) { 1356 block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number)) 1357 if block == nil { 1358 return "", fmt.Errorf("block #%d not found", number) 1359 } 1360 encoded, err := rlp.EncodeToBytes(block) 1361 if err != nil { 1362 return "", err 1363 } 1364 return fmt.Sprintf("%x", encoded), nil 1365 } 1366 1367 // PrintBlock retrieves a block and returns its pretty printed form. 1368 func (api *PublicDebugAPI) PrintBlock(ctx context.Context, number uint64) (string, error) { 1369 block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number)) 1370 if block == nil { 1371 return "", fmt.Errorf("block #%d not found", number) 1372 } 1373 return fmt.Sprintf("%s", block), nil 1374 } 1375 1376 // SeedHash retrieves the seed hash of a block. 1377 func (api *PublicDebugAPI) SeedHash(ctx context.Context, number uint64) (string, error) { 1378 block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number)) 1379 if block == nil { 1380 return "", fmt.Errorf("block #%d not found", number) 1381 } 1382 hash, err := ethash.GetSeedHash(number) 1383 if err != nil { 1384 return "", err 1385 } 1386 return fmt.Sprintf("0x%x", hash), nil 1387 } 1388 1389 // PrivateDebugAPI is the collection of Etheruem APIs exposed over the private 1390 // debugging endpoint. 1391 type PrivateDebugAPI struct { 1392 b Backend 1393 } 1394 1395 // NewPrivateDebugAPI creates a new API definition for the private debug methods 1396 // of the Ethereum service. 1397 func NewPrivateDebugAPI(b Backend) *PrivateDebugAPI { 1398 return &PrivateDebugAPI{b: b} 1399 } 1400 1401 // ChaindbProperty returns leveldb properties of the chain database. 1402 func (api *PrivateDebugAPI) ChaindbProperty(property string) (string, error) { 1403 ldb, ok := api.b.ChainDb().(interface { 1404 LDB() *leveldb.DB 1405 }) 1406 if !ok { 1407 return "", fmt.Errorf("chaindbProperty does not work for memory databases") 1408 } 1409 if property == "" { 1410 property = "leveldb.stats" 1411 } else if !strings.HasPrefix(property, "leveldb.") { 1412 property = "leveldb." + property 1413 } 1414 return ldb.LDB().GetProperty(property) 1415 } 1416 1417 func (api *PrivateDebugAPI) ChaindbCompact() error { 1418 ldb, ok := api.b.ChainDb().(interface { 1419 LDB() *leveldb.DB 1420 }) 1421 if !ok { 1422 return fmt.Errorf("chaindbCompact does not work for memory databases") 1423 } 1424 for b := byte(0); b < 255; b++ { 1425 glog.V(logger.Info).Infof("compacting chain DB range 0x%0.2X-0x%0.2X", b, b+1) 1426 err := ldb.LDB().CompactRange(util.Range{Start: []byte{b}, Limit: []byte{b + 1}}) 1427 if err != nil { 1428 glog.Errorf("compaction error: %v", err) 1429 return err 1430 } 1431 } 1432 return nil 1433 } 1434 1435 // SetHead rewinds the head of the blockchain to a previous block. 1436 func (api *PrivateDebugAPI) SetHead(number rpc.HexNumber) { 1437 api.b.SetHead(uint64(number.Int64())) 1438 } 1439 1440 // PublicNetAPI offers network related RPC methods 1441 type PublicNetAPI struct { 1442 net *p2p.Server 1443 networkVersion int 1444 } 1445 1446 // NewPublicNetAPI creates a new net API instance. 1447 func NewPublicNetAPI(net *p2p.Server, networkVersion int) *PublicNetAPI { 1448 return &PublicNetAPI{net, networkVersion} 1449 } 1450 1451 // Listening returns an indication if the node is listening for network connections. 1452 func (s *PublicNetAPI) Listening() bool { 1453 return true // always listening 1454 } 1455 1456 // PeerCount returns the number of connected peers 1457 func (s *PublicNetAPI) PeerCount() *rpc.HexNumber { 1458 return rpc.NewHexNumber(s.net.PeerCount()) 1459 } 1460 1461 // Version returns the current ethereum protocol version. 1462 func (s *PublicNetAPI) Version() string { 1463 return fmt.Sprintf("%d", s.networkVersion) 1464 }