github.com/codingfuture/orig-energi3@v0.8.4/internal/ethapi/api.go (about) 1 // Copyright 2018 The Energi Core Authors 2 // Copyright 2015 The go-ethereum Authors 3 // This file is part of the Energi Core library. 4 // 5 // The Energi Core library is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Lesser General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // The Energi Core library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Lesser General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public License 16 // along with the Energi Core library. If not, see <http://www.gnu.org/licenses/>. 17 18 package ethapi 19 20 import ( 21 "bytes" 22 "context" 23 "errors" 24 "fmt" 25 "math/big" 26 "strings" 27 "time" 28 29 "github.com/davecgh/go-spew/spew" 30 "github.com/ethereum/go-ethereum/accounts" 31 "github.com/ethereum/go-ethereum/accounts/keystore" 32 "github.com/ethereum/go-ethereum/common" 33 "github.com/ethereum/go-ethereum/common/hexutil" 34 "github.com/ethereum/go-ethereum/common/math" 35 "github.com/ethereum/go-ethereum/consensus/ethash" 36 "github.com/ethereum/go-ethereum/core" 37 "github.com/ethereum/go-ethereum/core/rawdb" 38 "github.com/ethereum/go-ethereum/core/types" 39 "github.com/ethereum/go-ethereum/core/vm" 40 "github.com/ethereum/go-ethereum/crypto" 41 "github.com/ethereum/go-ethereum/log" 42 "github.com/ethereum/go-ethereum/p2p" 43 "github.com/ethereum/go-ethereum/params" 44 "github.com/ethereum/go-ethereum/rlp" 45 "github.com/ethereum/go-ethereum/rpc" 46 "github.com/syndtr/goleveldb/leveldb" 47 "github.com/syndtr/goleveldb/leveldb/util" 48 49 energi_api "energi.world/core/gen3/energi/api" 50 ) 51 52 const ( 53 defaultGasPrice = params.GWei 54 capTraceInputLength = 64 * 1024 55 ) 56 57 // PublicEthereumAPI provides an API to access Ethereum related information. 58 // It offers only methods that operate on public data that is freely available to anyone. 59 type PublicEthereumAPI struct { 60 b Backend 61 } 62 63 // NewPublicEthereumAPI creates a new Ethereum protocol API. 64 func NewPublicEthereumAPI(b Backend) *PublicEthereumAPI { 65 return &PublicEthereumAPI{b} 66 } 67 68 // GasPrice returns a suggestion for a gas price. 69 func (s *PublicEthereumAPI) GasPrice(ctx context.Context) (*hexutil.Big, error) { 70 price, err := s.b.SuggestPrice(ctx) 71 return (*hexutil.Big)(price), err 72 } 73 74 // ProtocolVersion returns the current Ethereum protocol version this node supports 75 func (s *PublicEthereumAPI) ProtocolVersion() hexutil.Uint { 76 return hexutil.Uint(s.b.ProtocolVersion()) 77 } 78 79 // Syncing returns false in case the node is currently not syncing with the network. It can be up to date or has not 80 // yet received the latest block headers from its pears. In case it is synchronizing: 81 // - startingBlock: block number this node started to synchronise from 82 // - currentBlock: block number this node is currently importing 83 // - highestBlock: block number of the highest block header this node has received from peers 84 // - pulledStates: number of state entries processed until now 85 // - knownStates: number of known state entries that still need to be pulled 86 func (s *PublicEthereumAPI) Syncing() (interface{}, error) { 87 progress := s.b.Downloader().Progress() 88 89 // Return not syncing if the synchronisation already completed 90 if progress.CurrentBlock >= progress.HighestBlock { 91 return false, nil 92 } 93 // Otherwise gather the block sync stats 94 return map[string]interface{}{ 95 "startingBlock": hexutil.Uint64(progress.StartingBlock), 96 "currentBlock": hexutil.Uint64(progress.CurrentBlock), 97 "highestBlock": hexutil.Uint64(progress.HighestBlock), 98 "pulledStates": hexutil.Uint64(progress.PulledStates), 99 "knownStates": hexutil.Uint64(progress.KnownStates), 100 }, nil 101 } 102 103 // PublicTxPoolAPI offers and API for the transaction pool. It only operates on data that is non confidential. 104 type PublicTxPoolAPI struct { 105 b Backend 106 } 107 108 // NewPublicTxPoolAPI creates a new tx pool service that gives information about the transaction pool. 109 func NewPublicTxPoolAPI(b Backend) *PublicTxPoolAPI { 110 return &PublicTxPoolAPI{b} 111 } 112 113 // Content returns the transactions contained within the transaction pool. 114 func (s *PublicTxPoolAPI) Content() map[string]map[string]map[string]*RPCTransaction { 115 content := map[string]map[string]map[string]*RPCTransaction{ 116 "pending": make(map[string]map[string]*RPCTransaction), 117 "queued": make(map[string]map[string]*RPCTransaction), 118 } 119 pending, queue := s.b.TxPoolContent() 120 121 // Flatten the pending transactions 122 for account, txs := range pending { 123 dump := make(map[string]*RPCTransaction) 124 for _, tx := range txs { 125 dump[fmt.Sprintf("%d", tx.Nonce())] = newRPCPendingTransaction(tx) 126 } 127 content["pending"][account.Hex()] = dump 128 } 129 // Flatten the queued transactions 130 for account, txs := range queue { 131 dump := make(map[string]*RPCTransaction) 132 for _, tx := range txs { 133 dump[fmt.Sprintf("%d", tx.Nonce())] = newRPCPendingTransaction(tx) 134 } 135 content["queued"][account.Hex()] = dump 136 } 137 return content 138 } 139 140 // Status returns the number of pending and queued transaction in the pool. 141 func (s *PublicTxPoolAPI) Status() map[string]hexutil.Uint { 142 pending, queue := s.b.Stats() 143 return map[string]hexutil.Uint{ 144 "pending": hexutil.Uint(pending), 145 "queued": hexutil.Uint(queue), 146 } 147 } 148 149 // Inspect retrieves the content of the transaction pool and flattens it into an 150 // easily inspectable list. 151 func (s *PublicTxPoolAPI) Inspect() map[string]map[string]map[string]string { 152 content := map[string]map[string]map[string]string{ 153 "pending": make(map[string]map[string]string), 154 "queued": make(map[string]map[string]string), 155 } 156 pending, queue := s.b.TxPoolContent() 157 158 // Define a formatter to flatten a transaction into a string 159 var format = func(tx *types.Transaction) string { 160 if to := tx.To(); to != nil { 161 return fmt.Sprintf("%s: %v wei + %v gas × %v wei", tx.To().Hex(), tx.Value(), tx.Gas(), tx.GasPrice()) 162 } 163 return fmt.Sprintf("contract creation: %v wei + %v gas × %v wei", tx.Value(), tx.Gas(), tx.GasPrice()) 164 } 165 // Flatten the pending transactions 166 for account, txs := range pending { 167 dump := make(map[string]string) 168 for _, tx := range txs { 169 dump[fmt.Sprintf("%d", tx.Nonce())] = format(tx) 170 } 171 content["pending"][account.Hex()] = dump 172 } 173 // Flatten the queued transactions 174 for account, txs := range queue { 175 dump := make(map[string]string) 176 for _, tx := range txs { 177 dump[fmt.Sprintf("%d", tx.Nonce())] = format(tx) 178 } 179 content["queued"][account.Hex()] = dump 180 } 181 return content 182 } 183 184 // PublicAccountAPI provides an API to access accounts managed by this node. 185 // It offers only methods that can retrieve accounts. 186 type PublicAccountAPI struct { 187 am *accounts.Manager 188 } 189 190 // NewPublicAccountAPI creates a new PublicAccountAPI. 191 func NewPublicAccountAPI(am *accounts.Manager) *PublicAccountAPI { 192 return &PublicAccountAPI{am: am} 193 } 194 195 // Accounts returns the collection of accounts this node manages 196 func (s *PublicAccountAPI) Accounts() []common.Address { 197 addresses := make([]common.Address, 0) // return [] instead of nil if empty 198 for _, wallet := range s.am.Wallets() { 199 if _, ok := wallet.(*energi_api.EphemeralWallet); ok { 200 continue 201 } 202 for _, account := range wallet.Accounts() { 203 addresses = append(addresses, account.Address) 204 } 205 } 206 return addresses 207 } 208 209 // PrivateAccountAPI provides an API to access accounts managed by this node. 210 // It offers methods to create, (un)lock en list accounts. Some methods accept 211 // passwords and are therefore considered private by default. 212 type PrivateAccountAPI struct { 213 am *accounts.Manager 214 nonceLock *AddrLocker 215 b Backend 216 } 217 218 // NewPrivateAccountAPI create a new PrivateAccountAPI. 219 func NewPrivateAccountAPI(b Backend, nonceLock *AddrLocker) *PrivateAccountAPI { 220 return &PrivateAccountAPI{ 221 am: b.AccountManager(), 222 nonceLock: nonceLock, 223 b: b, 224 } 225 } 226 227 // ListAccounts will return a list of addresses for accounts this node manages. 228 func (s *PrivateAccountAPI) ListAccounts() []common.Address { 229 addresses := make([]common.Address, 0) // return [] instead of nil if empty 230 for _, wallet := range s.am.Wallets() { 231 if _, ok := wallet.(*energi_api.EphemeralWallet); ok { 232 continue 233 } 234 for _, account := range wallet.Accounts() { 235 addresses = append(addresses, account.Address) 236 } 237 } 238 return addresses 239 } 240 241 // rawWallet is a JSON representation of an accounts.Wallet interface, with its 242 // data contents extracted into plain fields. 243 type rawWallet struct { 244 URL string `json:"url"` 245 Status string `json:"status"` 246 Failure string `json:"failure,omitempty"` 247 Accounts []accounts.Account `json:"accounts,omitempty"` 248 } 249 250 // ListWallets will return a list of wallets this node manages. 251 func (s *PrivateAccountAPI) ListWallets() []rawWallet { 252 wallets := make([]rawWallet, 0) // return [] instead of nil if empty 253 for _, wallet := range s.am.Wallets() { 254 if _, ok := wallet.(*energi_api.EphemeralWallet); ok { 255 continue 256 } 257 258 status, failure := wallet.Status() 259 260 raw := rawWallet{ 261 URL: wallet.URL().String(), 262 Status: status, 263 Accounts: wallet.Accounts(), 264 } 265 if failure != nil { 266 raw.Failure = failure.Error() 267 } 268 wallets = append(wallets, raw) 269 } 270 return wallets 271 } 272 273 // OpenWallet initiates a hardware wallet opening procedure, establishing a USB 274 // connection and attempting to authenticate via the provided passphrase. Note, 275 // the method may return an extra challenge requiring a second open (e.g. the 276 // Trezor PIN matrix challenge). 277 func (s *PrivateAccountAPI) OpenWallet(url string, passphrase *string) error { 278 wallet, err := s.am.Wallet(url) 279 if err != nil { 280 return err 281 } 282 pass := "" 283 if passphrase != nil { 284 pass = *passphrase 285 } 286 return wallet.Open(pass) 287 } 288 289 // DeriveAccount requests a HD wallet to derive a new account, optionally pinning 290 // it for later reuse. 291 func (s *PrivateAccountAPI) DeriveAccount(url string, path string, pin *bool) (accounts.Account, error) { 292 wallet, err := s.am.Wallet(url) 293 if err != nil { 294 return accounts.Account{}, err 295 } 296 derivPath, err := accounts.ParseDerivationPath(path) 297 if err != nil { 298 return accounts.Account{}, err 299 } 300 if pin == nil { 301 pin = new(bool) 302 } 303 return wallet.Derive(derivPath, *pin) 304 } 305 306 // NewAccount will create a new account and returns the address for the new account. 307 func (s *PrivateAccountAPI) NewAccount(password string) (common.Address, error) { 308 acc, err := fetchKeystore(s.am).NewAccount(password) 309 if err == nil { 310 return acc.Address, nil 311 } 312 return common.Address{}, err 313 } 314 315 // fetchKeystore retrives the encrypted keystore from the account manager. 316 func fetchKeystore(am *accounts.Manager) *keystore.KeyStore { 317 return am.Backends(keystore.KeyStoreType)[0].(*keystore.KeyStore) 318 } 319 320 // ImportRawKey stores the given hex encoded ECDSA key into the key directory, 321 // encrypting it with the passphrase. 322 func (s *PrivateAccountAPI) ImportRawKey(privkey string, password string) (common.Address, error) { 323 key, err := crypto.HexToECDSA(privkey) 324 if err != nil { 325 return common.Address{}, err 326 } 327 acc, err := fetchKeystore(s.am).ImportECDSA(key, password) 328 return acc.Address, err 329 } 330 331 // UnlockAccount will unlock the account associated with the given address with 332 // the given password for duration seconds. If duration is nil it will use a 333 // default of 300 seconds. It returns an indication if the account was unlocked. 334 func (s *PrivateAccountAPI) UnlockAccount(addr common.Address, password string, duration *uint64, stakingOnly *bool) (bool, error) { 335 const max = uint64(time.Duration(math.MaxInt64) / time.Second) 336 var d time.Duration 337 if duration == nil { 338 d = 300 * time.Second 339 } else if *duration > max { 340 return false, errors.New("unlock duration too large") 341 } else { 342 d = time.Duration(*duration) * time.Second 343 } 344 so := false 345 if stakingOnly != nil { 346 so = *stakingOnly 347 } 348 err := fetchKeystore(s.am).TimedUnlock(accounts.Account{Address: addr}, password, d, so) 349 if err != nil { 350 log.Warn("Failed account unlock attempt", "address", addr, "err", err) 351 } 352 return err == nil, err 353 } 354 355 // LockAccount will lock the account associated with the given address when it's unlocked. 356 func (s *PrivateAccountAPI) LockAccount(addr common.Address) bool { 357 return fetchKeystore(s.am).Lock(addr) == nil 358 } 359 360 // signTransaction sets defaults and signs the given transaction 361 // NOTE: the caller needs to ensure that the nonceLock is held, if applicable, 362 // and release it after the transaction has been submitted to the tx pool 363 func (s *PrivateAccountAPI) signTransaction(ctx context.Context, args *SendTxArgs, passwd string) (*types.Transaction, error) { 364 // Look up the wallet containing the requested signer 365 account := accounts.Account{Address: args.From} 366 wallet, err := s.am.Find(account) 367 if err != nil { 368 return nil, err 369 } 370 // Set some sanity defaults and terminate on failure 371 if err := args.setDefaults(ctx, s.b); err != nil { 372 return nil, err 373 } 374 // Assemble the transaction and sign with the wallet 375 tx := args.toTransaction() 376 377 var chainID *big.Int 378 if config := s.b.ChainConfig(); config.IsEIP155(s.b.CurrentBlock().Number()) { 379 chainID = config.ChainID 380 } 381 return wallet.SignTxWithPassphrase(account, passwd, tx, chainID) 382 } 383 384 // SendTransaction will create a transaction from the given arguments and 385 // tries to sign it with the key associated with args.To. If the given passwd isn't 386 // able to decrypt the key it fails. 387 func (s *PrivateAccountAPI) SendTransaction(ctx context.Context, args SendTxArgs, passwd string) (common.Hash, error) { 388 if args.Nonce == nil { 389 // Hold the addresse's mutex around signing to prevent concurrent assignment of 390 // the same nonce to multiple accounts. 391 s.nonceLock.LockAddr(args.From) 392 defer s.nonceLock.UnlockAddr(args.From) 393 } 394 signed, err := s.signTransaction(ctx, &args, passwd) 395 if err != nil { 396 log.Warn("Failed transaction send attempt", "from", args.From, "to", args.To, "value", args.Value.ToInt(), "err", err) 397 return common.Hash{}, err 398 } 399 return submitTransaction(ctx, s.b, signed) 400 } 401 402 // SignTransaction will create a transaction from the given arguments and 403 // tries to sign it with the key associated with args.To. If the given passwd isn't 404 // able to decrypt the key it fails. The transaction is returned in RLP-form, not broadcast 405 // to other nodes 406 func (s *PrivateAccountAPI) SignTransaction(ctx context.Context, args SendTxArgs, passwd string) (*SignTransactionResult, error) { 407 // No need to obtain the noncelock mutex, since we won't be sending this 408 // tx into the transaction pool, but right back to the user 409 if args.Gas == nil { 410 return nil, fmt.Errorf("gas not specified") 411 } 412 if args.GasPrice == nil { 413 return nil, fmt.Errorf("gasPrice not specified") 414 } 415 if args.Nonce == nil { 416 return nil, fmt.Errorf("nonce not specified") 417 } 418 signed, err := s.signTransaction(ctx, &args, passwd) 419 if err != nil { 420 log.Warn("Failed transaction sign attempt", "from", args.From, "to", args.To, "value", args.Value.ToInt(), "err", err) 421 return nil, err 422 } 423 data, err := rlp.EncodeToBytes(signed) 424 if err != nil { 425 return nil, err 426 } 427 return &SignTransactionResult{data, signed}, nil 428 } 429 430 // signHash is a helper function that calculates a hash for the given message that can be 431 // safely used to calculate a signature from. 432 // 433 // The hash is calulcated as 434 // keccak256("\x17Energi Signed Message:\n"${message length}${message}). 435 // 436 // This gives context to the signed message and prevents signing of transactions. 437 func signHash(data []byte) []byte { 438 msg := fmt.Sprintf("\x17Energi Signed Message:\n%d%s", len(data), data) 439 return crypto.Keccak256([]byte(msg)) 440 } 441 442 // Sign calculates an Ethereum ECDSA signature for: 443 // keccack256("\x17Energi Signed Message:\n" + len(message) + message)) 444 // 445 // Note, the produced signature conforms to the secp256k1 curve R, S and V values, 446 // where the V value will be 27 or 28 for legacy reasons. 447 // 448 // The key used to calculate the signature is decrypted with the given password. 449 // 450 // https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_sign 451 func (s *PrivateAccountAPI) Sign(ctx context.Context, data hexutil.Bytes, addr common.Address, passwd string) (hexutil.Bytes, error) { 452 // Look up the wallet containing the requested signer 453 account := accounts.Account{Address: addr} 454 455 wallet, err := s.b.AccountManager().Find(account) 456 if err != nil { 457 return nil, err 458 } 459 // Assemble sign the data with the wallet 460 signature, err := wallet.SignHashWithPassphrase(account, passwd, signHash(data)) 461 if err != nil { 462 log.Warn("Failed data sign attempt", "address", addr, "err", err) 463 return nil, err 464 } 465 signature[64] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper 466 return signature, nil 467 } 468 469 // EcRecover returns the address for the account that was used to create the signature. 470 // Note, this function is compatible with eth_sign and personal_sign. As such it recovers 471 // the address of: 472 // hash = keccak256("\x17Energi Signed Message:\n"${message length}${message}) 473 // addr = ecrecover(hash, signature) 474 // 475 // Note, the signature must conform to the secp256k1 curve R, S and V values, where 476 // the V value must be 27 or 28 for legacy reasons. 477 // 478 // https://github.com/ethereum/go-ethereum/wiki/Management-APIs#personal_ecRecover 479 func (s *PrivateAccountAPI) EcRecover(ctx context.Context, data, sig hexutil.Bytes) (common.Address, error) { 480 if len(sig) != 65 { 481 return common.Address{}, fmt.Errorf("signature must be 65 bytes long") 482 } 483 if sig[64] != 27 && sig[64] != 28 { 484 return common.Address{}, fmt.Errorf("invalid Energi signature (V is not 27 or 28)") 485 } 486 sig[64] -= 27 // Transform yellow paper V from 27/28 to 0/1 487 488 rpk, err := crypto.SigToPub(signHash(data), sig) 489 if err != nil { 490 return common.Address{}, err 491 } 492 return crypto.PubkeyToAddress(*rpk), nil 493 } 494 495 // SignAndSendTransaction was renamed to SendTransaction. This method is deprecated 496 // and will be removed in the future. It primary goal is to give clients time to update. 497 func (s *PrivateAccountAPI) SignAndSendTransaction(ctx context.Context, args SendTxArgs, passwd string) (common.Hash, error) { 498 return s.SendTransaction(ctx, args, passwd) 499 } 500 501 // PublicBlockChainAPI provides an API to access the Ethereum blockchain. 502 // It offers only methods that operate on public data that is freely available to anyone. 503 type PublicBlockChainAPI struct { 504 b Backend 505 } 506 507 // NewPublicBlockChainAPI creates a new Ethereum blockchain API. 508 func NewPublicBlockChainAPI(b Backend) *PublicBlockChainAPI { 509 return &PublicBlockChainAPI{b} 510 } 511 512 // BlockNumber returns the block number of the chain head. 513 func (s *PublicBlockChainAPI) BlockNumber() hexutil.Uint64 { 514 header, _ := s.b.HeaderByNumber(context.Background(), rpc.LatestBlockNumber) // latest header should always be available 515 return hexutil.Uint64(header.Number.Uint64()) 516 } 517 518 // GetBalance returns the amount of wei for the given address in the state of the 519 // given block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta 520 // block numbers are also allowed. 521 func (s *PublicBlockChainAPI) GetBalance(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (*hexutil.Big, error) { 522 state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr) 523 if state == nil || err != nil { 524 return nil, err 525 } 526 return (*hexutil.Big)(state.GetBalance(address)), state.Error() 527 } 528 529 // Result structs for GetProof 530 type AccountResult struct { 531 Address common.Address `json:"address"` 532 AccountProof []string `json:"accountProof"` 533 Balance *hexutil.Big `json:"balance"` 534 CodeHash common.Hash `json:"codeHash"` 535 Nonce hexutil.Uint64 `json:"nonce"` 536 StorageHash common.Hash `json:"storageHash"` 537 StorageProof []StorageResult `json:"storageProof"` 538 } 539 type StorageResult struct { 540 Key string `json:"key"` 541 Value *hexutil.Big `json:"value"` 542 Proof []string `json:"proof"` 543 } 544 545 // GetProof returns the Merkle-proof for a given account and optionally some storage keys. 546 func (s *PublicBlockChainAPI) GetProof(ctx context.Context, address common.Address, storageKeys []string, blockNr rpc.BlockNumber) (*AccountResult, error) { 547 state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr) 548 if state == nil || err != nil { 549 return nil, err 550 } 551 552 storageTrie := state.StorageTrie(address) 553 storageHash := types.EmptyRootHash 554 codeHash := state.GetCodeHash(address) 555 storageProof := make([]StorageResult, len(storageKeys)) 556 557 // if we have a storageTrie, (which means the account exists), we can update the storagehash 558 if storageTrie != nil { 559 storageHash = storageTrie.Hash() 560 } else { 561 // no storageTrie means the account does not exist, so the codeHash is the hash of an empty bytearray. 562 codeHash = crypto.Keccak256Hash(nil) 563 } 564 565 // create the proof for the storageKeys 566 for i, key := range storageKeys { 567 if storageTrie != nil { 568 proof, storageError := state.GetStorageProof(address, common.HexToHash(key)) 569 if storageError != nil { 570 return nil, storageError 571 } 572 storageProof[i] = StorageResult{key, (*hexutil.Big)(state.GetState(address, common.HexToHash(key)).Big()), common.ToHexArray(proof)} 573 } else { 574 storageProof[i] = StorageResult{key, &hexutil.Big{}, []string{}} 575 } 576 } 577 578 // create the accountProof 579 accountProof, proofErr := state.GetProof(address) 580 if proofErr != nil { 581 return nil, proofErr 582 } 583 584 return &AccountResult{ 585 Address: address, 586 AccountProof: common.ToHexArray(accountProof), 587 Balance: (*hexutil.Big)(state.GetBalance(address)), 588 CodeHash: codeHash, 589 Nonce: hexutil.Uint64(state.GetNonce(address)), 590 StorageHash: storageHash, 591 StorageProof: storageProof, 592 }, state.Error() 593 } 594 595 // GetBlockByNumber returns the requested block. When blockNr is -1 the chain head is returned. When fullTx is true all 596 // transactions in the block are returned in full detail, otherwise only the transaction hash is returned. 597 func (s *PublicBlockChainAPI) GetBlockByNumber(ctx context.Context, blockNr rpc.BlockNumber, fullTx bool) (map[string]interface{}, error) { 598 block, err := s.b.BlockByNumber(ctx, blockNr) 599 if block != nil { 600 response, err := s.rpcOutputBlock(block, true, fullTx) 601 if err == nil && blockNr == rpc.PendingBlockNumber { 602 // Pending blocks need to nil out a few fields 603 for _, field := range []string{"hash", "nonce", "miner"} { 604 response[field] = nil 605 } 606 } 607 return response, err 608 } 609 return nil, err 610 } 611 612 // GetBlockByHash returns the requested block. When fullTx is true all transactions in the block are returned in full 613 // detail, otherwise only the transaction hash is returned. 614 func (s *PublicBlockChainAPI) GetBlockByHash(ctx context.Context, blockHash common.Hash, fullTx bool) (map[string]interface{}, error) { 615 block, err := s.b.GetBlock(ctx, blockHash) 616 if block != nil { 617 return s.rpcOutputBlock(block, true, fullTx) 618 } 619 return nil, err 620 } 621 622 // GetUncleByBlockNumberAndIndex returns the uncle block for the given block hash and index. When fullTx is true 623 // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned. 624 func (s *PublicBlockChainAPI) GetUncleByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) (map[string]interface{}, error) { 625 block, err := s.b.BlockByNumber(ctx, blockNr) 626 if block != nil { 627 uncles := block.Uncles() 628 if index >= hexutil.Uint(len(uncles)) { 629 log.Debug("Requested uncle not found", "number", blockNr, "hash", block.Hash(), "index", index) 630 return nil, nil 631 } 632 block = types.NewBlockWithHeader(uncles[index]) 633 return s.rpcOutputBlock(block, false, false) 634 } 635 return nil, err 636 } 637 638 // GetUncleByBlockHashAndIndex returns the uncle block for the given block hash and index. When fullTx is true 639 // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned. 640 func (s *PublicBlockChainAPI) GetUncleByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) (map[string]interface{}, error) { 641 block, err := s.b.GetBlock(ctx, blockHash) 642 if block != nil { 643 uncles := block.Uncles() 644 if index >= hexutil.Uint(len(uncles)) { 645 log.Debug("Requested uncle not found", "number", block.Number(), "hash", blockHash, "index", index) 646 return nil, nil 647 } 648 block = types.NewBlockWithHeader(uncles[index]) 649 return s.rpcOutputBlock(block, false, false) 650 } 651 return nil, err 652 } 653 654 // GetUncleCountByBlockNumber returns number of uncles in the block for the given block number 655 func (s *PublicBlockChainAPI) GetUncleCountByBlockNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint { 656 if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil { 657 n := hexutil.Uint(len(block.Uncles())) 658 return &n 659 } 660 return nil 661 } 662 663 // GetUncleCountByBlockHash returns number of uncles in the block for the given block hash 664 func (s *PublicBlockChainAPI) GetUncleCountByBlockHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint { 665 if block, _ := s.b.GetBlock(ctx, blockHash); block != nil { 666 n := hexutil.Uint(len(block.Uncles())) 667 return &n 668 } 669 return nil 670 } 671 672 // GetCode returns the code stored at the given address in the state for the given block number. 673 func (s *PublicBlockChainAPI) GetCode(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (hexutil.Bytes, error) { 674 state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr) 675 if state == nil || err != nil { 676 return nil, err 677 } 678 code := state.GetCode(address) 679 return code, state.Error() 680 } 681 682 // GetStorageAt returns the storage from the state at the given address, key and 683 // block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta block 684 // numbers are also allowed. 685 func (s *PublicBlockChainAPI) GetStorageAt(ctx context.Context, address common.Address, key string, blockNr rpc.BlockNumber) (hexutil.Bytes, error) { 686 state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr) 687 if state == nil || err != nil { 688 return nil, err 689 } 690 res := state.GetState(address, common.HexToHash(key)) 691 return res[:], state.Error() 692 } 693 694 // CallArgs represents the arguments for a call. 695 type CallArgs struct { 696 From common.Address `json:"from"` 697 To *common.Address `json:"to"` 698 Gas hexutil.Uint64 `json:"gas"` 699 GasPrice hexutil.Big `json:"gasPrice"` 700 Value hexutil.Big `json:"value"` 701 Data hexutil.Bytes `json:"data"` 702 } 703 704 func (s *PublicBlockChainAPI) doCall(ctx context.Context, args CallArgs, blockNr rpc.BlockNumber, timeout time.Duration, globalGasCap *big.Int) ([]byte, uint64, bool, error) { 705 defer func(start time.Time) { log.Debug("Executing EVM call finished", "runtime", time.Since(start)) }(time.Now()) 706 707 state, header, err := s.b.StateAndHeaderByNumber(ctx, blockNr) 708 if state == nil || err != nil { 709 return nil, 0, false, err 710 } 711 // Set sender address or use a default if none specified 712 addr := args.From 713 if addr == (common.Address{}) { 714 if wallets := s.b.AccountManager().Wallets(); len(wallets) > 0 { 715 if accounts := wallets[0].Accounts(); len(accounts) > 0 { 716 addr = accounts[0].Address 717 } 718 } 719 } 720 // Set default gas & gas price if none were set 721 gas := uint64(args.Gas) 722 if gas == 0 { 723 gas = math.MaxUint64 / 2 724 } 725 if globalGasCap != nil && globalGasCap.Uint64() < gas { 726 log.Warn("Caller gas above allowance, capping", "requested", gas, "cap", globalGasCap) 727 gas = globalGasCap.Uint64() 728 } 729 gasPrice := args.GasPrice.ToInt() 730 if gasPrice.Sign() == 0 { 731 gasPrice = new(big.Int).SetUint64(defaultGasPrice) 732 } 733 // Create new call message 734 msg := types.NewMessage(addr, args.To, 0, args.Value.ToInt(), gas, gasPrice, args.Data, false) 735 736 // Setup context so it may be cancelled the call has completed 737 // or, in case of unmetered gas, setup a context with a timeout. 738 var cancel context.CancelFunc 739 if timeout > 0 { 740 ctx, cancel = context.WithTimeout(ctx, timeout) 741 } else { 742 ctx, cancel = context.WithCancel(ctx) 743 } 744 // Make sure the context is cancelled when the call has completed 745 // this makes sure resources are cleaned up. 746 defer cancel() 747 748 // Get a new instance of the EVM. 749 evm, vmError, err := s.b.GetEVM(ctx, msg, state, header) 750 if err != nil { 751 return nil, 0, false, err 752 } 753 // Wait for the context to be done and cancel the evm. Even if the 754 // EVM has finished, cancelling may be done (repeatedly) 755 go func() { 756 <-ctx.Done() 757 evm.Cancel() 758 }() 759 760 // Setup the gas pool (also for unmetered requests) 761 // and apply the message. 762 gp := new(core.GasPool).AddGas(math.MaxUint64) 763 res, gas, failed, err := core.ApplyMessage(evm, msg, gp) 764 if err := vmError(); err != nil { 765 return nil, 0, false, err 766 } 767 return res, gas, failed, err 768 } 769 770 // Call executes the given transaction on the state for the given block number. 771 // It doesn't make and changes in the state/blockchain and is useful to execute and retrieve values. 772 func (s *PublicBlockChainAPI) Call(ctx context.Context, args CallArgs, blockNr rpc.BlockNumber) (hexutil.Bytes, error) { 773 result, _, _, err := s.doCall(ctx, args, blockNr, 5*time.Second, s.b.RPCGasCap()) 774 return (hexutil.Bytes)(result), err 775 } 776 777 // EstimateGas returns an estimate of the amount of gas needed to execute the 778 // given transaction against the current pending block. 779 func (s *PublicBlockChainAPI) EstimateGas(ctx context.Context, args CallArgs) (hexutil.Uint64, error) { 780 // Binary search the gas requirement, as it may be higher than the amount used 781 var ( 782 lo uint64 = params.TxGas - 1 783 hi uint64 784 cap uint64 785 ) 786 if uint64(args.Gas) >= params.TxGas { 787 hi = uint64(args.Gas) 788 } else { 789 // Retrieve the current pending block to act as the gas ceiling 790 block, err := s.b.BlockByNumber(ctx, rpc.PendingBlockNumber) 791 if err != nil { 792 return 0, err 793 } 794 hi = block.GasLimit() 795 } 796 gasCap := s.b.RPCGasCap() 797 if gasCap != nil && hi > gasCap.Uint64() { 798 log.Warn("Caller gas above allowance, capping", "requested", hi, "cap", gasCap) 799 hi = gasCap.Uint64() 800 } 801 cap = hi 802 803 // Create a helper to check if a gas allowance results in an executable transaction 804 executable := func(gas uint64) bool { 805 args.Gas = hexutil.Uint64(gas) 806 807 _, _, failed, err := s.doCall(ctx, args, rpc.PendingBlockNumber, 0, gasCap) 808 if err != nil || failed { 809 return false 810 } 811 return true 812 } 813 // Execute the binary search and hone in on an executable gas limit 814 for lo+1 < hi { 815 mid := (hi + lo) / 2 816 if !executable(mid) { 817 lo = mid 818 } else { 819 hi = mid 820 } 821 } 822 // Reject the transaction as invalid if it still fails at the highest allowance 823 if hi == cap { 824 if !executable(hi) { 825 return 0, fmt.Errorf("gas required exceeds allowance (%d) or always failing transaction", cap) 826 } 827 } 828 return hexutil.Uint64(hi), nil 829 } 830 831 // ExecutionResult groups all structured logs emitted by the EVM 832 // while replaying a transaction in debug mode as well as transaction 833 // execution status, the amount of gas used and the return value 834 type ExecutionResult struct { 835 Gas uint64 `json:"gas"` 836 Failed bool `json:"failed"` 837 ReturnValue string `json:"returnValue"` 838 StructLogs []StructLogRes `json:"structLogs"` 839 } 840 841 // StructLogRes stores a structured log emitted by the EVM while replaying a 842 // transaction in debug mode 843 type StructLogRes struct { 844 Pc uint64 `json:"pc"` 845 Op string `json:"op"` 846 Gas uint64 `json:"gas"` 847 GasCost uint64 `json:"gasCost"` 848 Depth int `json:"depth"` 849 Error error `json:"error,omitempty"` 850 Stack *[]string `json:"stack,omitempty"` 851 Memory *[]string `json:"memory,omitempty"` 852 Storage *map[string]string `json:"storage,omitempty"` 853 } 854 855 // formatLogs formats EVM returned structured logs for json output 856 func FormatLogs(logs []vm.StructLog) []StructLogRes { 857 formatted := make([]StructLogRes, len(logs)) 858 for index, trace := range logs { 859 formatted[index] = StructLogRes{ 860 Pc: trace.Pc, 861 Op: trace.Op.String(), 862 Gas: trace.Gas, 863 GasCost: trace.GasCost, 864 Depth: trace.Depth, 865 Error: trace.Err, 866 } 867 if trace.Stack != nil { 868 stack := make([]string, len(trace.Stack)) 869 for i, stackValue := range trace.Stack { 870 stack[i] = fmt.Sprintf("%x", math.PaddedBigBytes(stackValue, 32)) 871 } 872 formatted[index].Stack = &stack 873 } 874 if trace.Memory != nil { 875 memory := make([]string, 0, (len(trace.Memory)+31)/32) 876 for i := 0; i+32 <= len(trace.Memory); i += 32 { 877 memory = append(memory, fmt.Sprintf("%x", trace.Memory[i:i+32])) 878 } 879 formatted[index].Memory = &memory 880 } 881 if trace.Storage != nil { 882 storage := make(map[string]string) 883 for i, storageValue := range trace.Storage { 884 storage[fmt.Sprintf("%x", i)] = fmt.Sprintf("%x", storageValue) 885 } 886 formatted[index].Storage = &storage 887 } 888 } 889 return formatted 890 } 891 892 // RPCMarshalBlock converts the given block to the RPC output which depends on fullTx. If inclTx is true transactions are 893 // returned. When fullTx is true the returned block contains full transaction details, otherwise it will only contain 894 // transaction hashes. 895 func RPCMarshalBlock(b *types.Block, inclTx bool, fullTx bool) (map[string]interface{}, error) { 896 head := b.Header() // copies the header once 897 fields := map[string]interface{}{ 898 "number": (*hexutil.Big)(head.Number), 899 "hash": b.Hash(), 900 "parentHash": head.ParentHash, 901 "nonce": head.Nonce, 902 "mixHash": head.MixDigest, 903 "sha3Uncles": head.UncleHash, 904 "logsBloom": head.Bloom, 905 "stateRoot": head.Root, 906 "miner": head.Coinbase, 907 "difficulty": (*hexutil.Big)(head.Difficulty), 908 "extraData": hexutil.Bytes(head.Extra), 909 "size": hexutil.Uint64(b.Size()), 910 "gasLimit": hexutil.Uint64(head.GasLimit), 911 "gasUsed": hexutil.Uint64(head.GasUsed), 912 "timestamp": hexutil.Uint64(head.Time), 913 "transactionsRoot": head.TxHash, 914 "receiptsRoot": head.ReceiptHash, 915 } 916 917 if len(head.Signature) > 0 { 918 fields["signature"] = hexutil.Bytes(head.Signature) 919 } 920 921 if inclTx { 922 formatTx := func(tx *types.Transaction) (interface{}, error) { 923 return tx.Hash(), nil 924 } 925 if fullTx { 926 formatTx = func(tx *types.Transaction) (interface{}, error) { 927 return newRPCTransactionFromBlockHash(b, tx.Hash()), nil 928 } 929 } 930 txs := b.Transactions() 931 transactions := make([]interface{}, len(txs)) 932 var err error 933 for i, tx := range txs { 934 if transactions[i], err = formatTx(tx); err != nil { 935 return nil, err 936 } 937 } 938 fields["transactions"] = transactions 939 } 940 941 uncles := b.Uncles() 942 uncleHashes := make([]common.Hash, len(uncles)) 943 for i, uncle := range uncles { 944 uncleHashes[i] = uncle.Hash() 945 } 946 fields["uncles"] = uncleHashes 947 948 return fields, nil 949 } 950 951 // rpcOutputBlock uses the generalized output filler, then adds the total difficulty field, which requires 952 // a `PublicBlockchainAPI`. 953 func (s *PublicBlockChainAPI) rpcOutputBlock(b *types.Block, inclTx bool, fullTx bool) (map[string]interface{}, error) { 954 fields, err := RPCMarshalBlock(b, inclTx, fullTx) 955 if err != nil { 956 return nil, err 957 } 958 fields["totalDifficulty"] = (*hexutil.Big)(s.b.GetTd(b.Hash())) 959 return fields, err 960 } 961 962 // RPCTransaction represents a transaction that will serialize to the RPC representation of a transaction 963 type RPCTransaction struct { 964 BlockHash common.Hash `json:"blockHash"` 965 BlockNumber *hexutil.Big `json:"blockNumber"` 966 From common.Address `json:"from"` 967 Gas hexutil.Uint64 `json:"gas"` 968 GasPrice *hexutil.Big `json:"gasPrice"` 969 Hash common.Hash `json:"hash"` 970 Input hexutil.Bytes `json:"input"` 971 Nonce hexutil.Uint64 `json:"nonce"` 972 To *common.Address `json:"to"` 973 TransactionIndex hexutil.Uint `json:"transactionIndex"` 974 Value *hexutil.Big `json:"value"` 975 V *hexutil.Big `json:"v"` 976 R *hexutil.Big `json:"r"` 977 S *hexutil.Big `json:"s"` 978 979 // Causes troubles for external tools 980 //consensus bool `json:"consensus,omitempty"` 981 } 982 983 // newRPCTransaction returns a transaction that will serialize to the RPC 984 // representation, with the given location metadata set (if available). 985 func newRPCTransaction(tx *types.Transaction, blockHash common.Hash, blockNumber uint64, index uint64) *RPCTransaction { 986 var signer types.Signer = types.FrontierSigner{} 987 if tx.Protected() { 988 signer = types.NewEIP155Signer(tx.ChainId()) 989 } 990 from, _ := types.Sender(signer, tx) 991 v, r, s := tx.RawSignatureValues() 992 993 consensus := tx.IsConsensus() 994 if consensus { 995 from = tx.ConsensusSender() 996 } 997 998 tx_data := tx.Data() 999 if len(tx_data) > capTraceInputLength { 1000 tx_data = tx_data[:capTraceInputLength] 1001 } 1002 1003 result := &RPCTransaction{ 1004 From: from, 1005 Gas: hexutil.Uint64(tx.Gas()), 1006 GasPrice: (*hexutil.Big)(tx.GasPrice()), 1007 Hash: tx.Hash(), 1008 Input: hexutil.Bytes(tx_data), 1009 Nonce: hexutil.Uint64(tx.Nonce()), 1010 To: tx.To(), 1011 Value: (*hexutil.Big)(tx.Value()), 1012 V: (*hexutil.Big)(v), 1013 R: (*hexutil.Big)(r), 1014 S: (*hexutil.Big)(s), 1015 // Energi-specific 1016 //consensus: consensus, 1017 } 1018 if blockHash != (common.Hash{}) { 1019 result.BlockHash = blockHash 1020 result.BlockNumber = (*hexutil.Big)(new(big.Int).SetUint64(blockNumber)) 1021 result.TransactionIndex = hexutil.Uint(index) 1022 } 1023 return result 1024 } 1025 1026 // newRPCPendingTransaction returns a pending transaction that will serialize to the RPC representation 1027 func newRPCPendingTransaction(tx *types.Transaction) *RPCTransaction { 1028 return newRPCTransaction(tx, common.Hash{}, 0, 0) 1029 } 1030 1031 // newRPCTransactionFromBlockIndex returns a transaction that will serialize to the RPC representation. 1032 func newRPCTransactionFromBlockIndex(b *types.Block, index uint64) *RPCTransaction { 1033 txs := b.Transactions() 1034 if index >= uint64(len(txs)) { 1035 return nil 1036 } 1037 return newRPCTransaction(txs[index], b.Hash(), b.NumberU64(), index) 1038 } 1039 1040 // newRPCRawTransactionFromBlockIndex returns the bytes of a transaction given a block and a transaction index. 1041 func newRPCRawTransactionFromBlockIndex(b *types.Block, index uint64) hexutil.Bytes { 1042 txs := b.Transactions() 1043 if index >= uint64(len(txs)) { 1044 return nil 1045 } 1046 blob, _ := rlp.EncodeToBytes(txs[index]) 1047 return blob 1048 } 1049 1050 // newRPCTransactionFromBlockHash returns a transaction that will serialize to the RPC representation. 1051 func newRPCTransactionFromBlockHash(b *types.Block, hash common.Hash) *RPCTransaction { 1052 for idx, tx := range b.Transactions() { 1053 if tx.Hash() == hash { 1054 return newRPCTransactionFromBlockIndex(b, uint64(idx)) 1055 } 1056 } 1057 return nil 1058 } 1059 1060 // PublicTransactionPoolAPI exposes methods for the RPC interface 1061 type PublicTransactionPoolAPI struct { 1062 b Backend 1063 nonceLock *AddrLocker 1064 } 1065 1066 // NewPublicTransactionPoolAPI creates a new RPC service with methods specific for the transaction pool. 1067 func NewPublicTransactionPoolAPI(b Backend, nonceLock *AddrLocker) *PublicTransactionPoolAPI { 1068 return &PublicTransactionPoolAPI{b, nonceLock} 1069 } 1070 1071 // GetBlockTransactionCountByNumber returns the number of transactions in the block with the given block number. 1072 func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint { 1073 if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil { 1074 n := hexutil.Uint(len(block.Transactions())) 1075 return &n 1076 } 1077 return nil 1078 } 1079 1080 // GetBlockTransactionCountByHash returns the number of transactions in the block with the given hash. 1081 func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint { 1082 if block, _ := s.b.GetBlock(ctx, blockHash); block != nil { 1083 n := hexutil.Uint(len(block.Transactions())) 1084 return &n 1085 } 1086 return nil 1087 } 1088 1089 // GetTransactionByBlockNumberAndIndex returns the transaction for the given block number and index. 1090 func (s *PublicTransactionPoolAPI) GetTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) *RPCTransaction { 1091 if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil { 1092 return newRPCTransactionFromBlockIndex(block, uint64(index)) 1093 } 1094 return nil 1095 } 1096 1097 // GetTransactionByBlockHashAndIndex returns the transaction for the given block hash and index. 1098 func (s *PublicTransactionPoolAPI) GetTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) *RPCTransaction { 1099 if block, _ := s.b.GetBlock(ctx, blockHash); block != nil { 1100 return newRPCTransactionFromBlockIndex(block, uint64(index)) 1101 } 1102 return nil 1103 } 1104 1105 // GetRawTransactionByBlockNumberAndIndex returns the bytes of the transaction for the given block number and index. 1106 func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) hexutil.Bytes { 1107 if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil { 1108 return newRPCRawTransactionFromBlockIndex(block, uint64(index)) 1109 } 1110 return nil 1111 } 1112 1113 // GetRawTransactionByBlockHashAndIndex returns the bytes of the transaction for the given block hash and index. 1114 func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) hexutil.Bytes { 1115 if block, _ := s.b.GetBlock(ctx, blockHash); block != nil { 1116 return newRPCRawTransactionFromBlockIndex(block, uint64(index)) 1117 } 1118 return nil 1119 } 1120 1121 // GetTransactionCount returns the number of transactions the given address has sent for the given block number 1122 func (s *PublicTransactionPoolAPI) GetTransactionCount(ctx context.Context, address common.Address, blockNr rpc.BlockNumber) (*hexutil.Uint64, error) { 1123 // Ask transaction pool for the nonce which includes pending transactions 1124 if blockNr == rpc.PendingBlockNumber { 1125 nonce, err := s.b.GetPoolNonce(ctx, address) 1126 if err != nil { 1127 return nil, err 1128 } 1129 return (*hexutil.Uint64)(&nonce), nil 1130 } 1131 // Resolve block number and use its state to ask for the nonce 1132 state, _, err := s.b.StateAndHeaderByNumber(ctx, blockNr) 1133 if state == nil || err != nil { 1134 return nil, err 1135 } 1136 nonce := state.GetNonce(address) 1137 return (*hexutil.Uint64)(&nonce), state.Error() 1138 } 1139 1140 // GetTransactionByHash returns the transaction for the given hash 1141 func (s *PublicTransactionPoolAPI) GetTransactionByHash(ctx context.Context, hash common.Hash) *RPCTransaction { 1142 // Try to return an already finalized transaction 1143 if tx, blockHash, blockNumber, index := rawdb.ReadTransaction(s.b.ChainDb(), hash); tx != nil { 1144 return newRPCTransaction(tx, blockHash, blockNumber, index) 1145 } 1146 // No finalized transaction, try to retrieve it from the pool 1147 if tx := s.b.GetPoolTransaction(hash); tx != nil { 1148 return newRPCPendingTransaction(tx) 1149 } 1150 // Transaction unknown, return as such 1151 return nil 1152 } 1153 1154 // GetRawTransactionByHash returns the bytes of the transaction for the given hash. 1155 func (s *PublicTransactionPoolAPI) GetRawTransactionByHash(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) { 1156 var tx *types.Transaction 1157 1158 // Retrieve a finalized transaction, or a pooled otherwise 1159 if tx, _, _, _ = rawdb.ReadTransaction(s.b.ChainDb(), hash); tx == nil { 1160 if tx = s.b.GetPoolTransaction(hash); tx == nil { 1161 // Transaction not found anywhere, abort 1162 return nil, nil 1163 } 1164 } 1165 // Serialize to RLP and return 1166 return rlp.EncodeToBytes(tx) 1167 } 1168 1169 // GetTransactionReceipt returns the transaction receipt for the given transaction hash. 1170 func (s *PublicTransactionPoolAPI) GetTransactionReceipt(ctx context.Context, hash common.Hash) (map[string]interface{}, error) { 1171 tx, blockHash, blockNumber, index := rawdb.ReadTransaction(s.b.ChainDb(), hash) 1172 if tx == nil { 1173 return nil, nil 1174 } 1175 receipts, err := s.b.GetReceipts(ctx, blockHash) 1176 if err != nil { 1177 return nil, err 1178 } 1179 if len(receipts) <= int(index) { 1180 return nil, nil 1181 } 1182 receipt := receipts[index] 1183 1184 var signer types.Signer = types.FrontierSigner{} 1185 if tx.Protected() { 1186 signer = types.NewEIP155Signer(tx.ChainId()) 1187 } 1188 from, _ := types.Sender(signer, tx) 1189 1190 consensus := tx.IsConsensus() 1191 if consensus { 1192 from = tx.ConsensusSender() 1193 } 1194 1195 fields := map[string]interface{}{ 1196 "blockHash": blockHash, 1197 "blockNumber": hexutil.Uint64(blockNumber), 1198 "transactionHash": hash, 1199 "transactionIndex": hexutil.Uint64(index), 1200 "from": from, 1201 "to": tx.To(), 1202 "gasUsed": hexutil.Uint64(receipt.GasUsed), 1203 "cumulativeGasUsed": hexutil.Uint64(receipt.CumulativeGasUsed), 1204 "contractAddress": nil, 1205 "logs": receipt.Logs, 1206 "logsBloom": receipt.Bloom, 1207 } 1208 1209 // Assign receipt status or post state. 1210 if len(receipt.PostState) > 0 { 1211 fields["root"] = hexutil.Bytes(receipt.PostState) 1212 } else { 1213 fields["status"] = hexutil.Uint(receipt.Status) 1214 } 1215 if receipt.Logs == nil { 1216 fields["logs"] = [][]*types.Log{} 1217 } 1218 // If the ContractAddress is 20 0x0 bytes, assume it is not a contract creation 1219 if receipt.ContractAddress != (common.Address{}) { 1220 fields["contractAddress"] = receipt.ContractAddress 1221 } 1222 // NOTE: it causes troubles for external tools for now. 1223 // if consensus { 1224 // fields["consensus"] = consensus 1225 // } 1226 return fields, nil 1227 } 1228 1229 // sign is a helper function that signs a transaction with the private key of the given address. 1230 func (s *PublicTransactionPoolAPI) sign(addr common.Address, tx *types.Transaction) (*types.Transaction, error) { 1231 // Look up the wallet containing the requested signer 1232 account := accounts.Account{Address: addr} 1233 1234 wallet, err := s.b.AccountManager().Find(account) 1235 if err != nil { 1236 return nil, err 1237 } 1238 // Request the wallet to sign the transaction 1239 var chainID *big.Int 1240 if config := s.b.ChainConfig(); config.IsEIP155(s.b.CurrentBlock().Number()) { 1241 chainID = config.ChainID 1242 } 1243 return wallet.SignTx(account, tx, chainID) 1244 } 1245 1246 // SendTxArgs represents the arguments to sumbit a new transaction into the transaction pool. 1247 type SendTxArgs struct { 1248 From common.Address `json:"from"` 1249 To *common.Address `json:"to"` 1250 Gas *hexutil.Uint64 `json:"gas"` 1251 GasPrice *hexutil.Big `json:"gasPrice"` 1252 Value *hexutil.Big `json:"value"` 1253 Nonce *hexutil.Uint64 `json:"nonce"` 1254 // We accept "data" and "input" for backwards-compatibility reasons. "input" is the 1255 // newer name and should be preferred by clients. 1256 Data *hexutil.Bytes `json:"data"` 1257 Input *hexutil.Bytes `json:"input"` 1258 } 1259 1260 // setDefaults is a helper function that fills in default values for unspecified tx fields. 1261 func (args *SendTxArgs) setDefaults(ctx context.Context, b Backend) error { 1262 if args.Gas == nil { 1263 args.Gas = new(hexutil.Uint64) 1264 *(*uint64)(args.Gas) = 90000 1265 } 1266 if args.GasPrice == nil { 1267 price, err := b.SuggestPrice(ctx) 1268 if err != nil { 1269 return err 1270 } 1271 args.GasPrice = (*hexutil.Big)(price) 1272 } 1273 if args.Value == nil { 1274 args.Value = new(hexutil.Big) 1275 } 1276 if args.Nonce == nil { 1277 nonce, err := b.GetPoolNonce(ctx, args.From) 1278 if err != nil { 1279 return err 1280 } 1281 args.Nonce = (*hexutil.Uint64)(&nonce) 1282 } 1283 if args.Data != nil && args.Input != nil && !bytes.Equal(*args.Data, *args.Input) { 1284 return errors.New(`Both "data" and "input" are set and not equal. Please use "input" to pass transaction call data.`) 1285 } 1286 if args.To == nil { 1287 // Contract creation 1288 var input []byte 1289 if args.Data != nil { 1290 input = *args.Data 1291 } else if args.Input != nil { 1292 input = *args.Input 1293 } 1294 if len(input) == 0 { 1295 return errors.New(`contract creation without any data provided`) 1296 } 1297 } 1298 return nil 1299 } 1300 1301 func (args *SendTxArgs) toTransaction() *types.Transaction { 1302 var input []byte 1303 if args.Data != nil { 1304 input = *args.Data 1305 } else if args.Input != nil { 1306 input = *args.Input 1307 } 1308 if args.To == nil { 1309 return types.NewContractCreation(uint64(*args.Nonce), (*big.Int)(args.Value), uint64(*args.Gas), (*big.Int)(args.GasPrice), input) 1310 } 1311 return types.NewTransaction(uint64(*args.Nonce), *args.To, (*big.Int)(args.Value), uint64(*args.Gas), (*big.Int)(args.GasPrice), input) 1312 } 1313 1314 // submitTransaction is a helper function that submits tx to txPool and logs a message. 1315 func submitTransaction(ctx context.Context, b Backend, tx *types.Transaction) (common.Hash, error) { 1316 if err := b.SendTx(ctx, tx); err != nil { 1317 return common.Hash{}, err 1318 } 1319 if tx.To() == nil { 1320 signer := types.MakeSigner(b.ChainConfig(), b.CurrentBlock().Number()) 1321 from, err := types.Sender(signer, tx) 1322 if err != nil { 1323 return common.Hash{}, err 1324 } 1325 addr := crypto.CreateAddress(from, tx.Nonce()) 1326 log.Info("Submitted contract creation", "fullhash", tx.Hash().Hex(), "contract", addr.Hex()) 1327 } else { 1328 log.Info("Submitted transaction", "fullhash", tx.Hash().Hex(), "recipient", tx.To()) 1329 } 1330 return tx.Hash(), nil 1331 } 1332 1333 // SendTransaction creates a transaction for the given argument, sign it and submit it to the 1334 // transaction pool. 1335 func (s *PublicTransactionPoolAPI) SendTransaction(ctx context.Context, args SendTxArgs) (common.Hash, error) { 1336 1337 // Look up the wallet containing the requested signer 1338 account := accounts.Account{Address: args.From} 1339 1340 wallet, err := s.b.AccountManager().Find(account) 1341 if err != nil { 1342 return common.Hash{}, err 1343 } 1344 1345 if args.Nonce == nil { 1346 // Hold the addresse's mutex around signing to prevent concurrent assignment of 1347 // the same nonce to multiple accounts. 1348 s.nonceLock.LockAddr(args.From) 1349 defer s.nonceLock.UnlockAddr(args.From) 1350 } 1351 1352 // Set some sanity defaults and terminate on failure 1353 if err := args.setDefaults(ctx, s.b); err != nil { 1354 return common.Hash{}, err 1355 } 1356 // Assemble the transaction and sign with the wallet 1357 tx := args.toTransaction() 1358 1359 var chainID *big.Int 1360 if config := s.b.ChainConfig(); config.IsEIP155(s.b.CurrentBlock().Number()) { 1361 chainID = config.ChainID 1362 } 1363 signed, err := wallet.SignTx(account, tx, chainID) 1364 if err != nil { 1365 return common.Hash{}, err 1366 } 1367 return submitTransaction(ctx, s.b, signed) 1368 } 1369 1370 // SendRawTransaction will add the signed transaction to the transaction pool. 1371 // The sender is responsible for signing the transaction and using the correct nonce. 1372 func (s *PublicTransactionPoolAPI) SendRawTransaction(ctx context.Context, encodedTx hexutil.Bytes) (common.Hash, error) { 1373 tx := new(types.Transaction) 1374 if err := rlp.DecodeBytes(encodedTx, tx); err != nil { 1375 return common.Hash{}, err 1376 } 1377 return submitTransaction(ctx, s.b, tx) 1378 } 1379 1380 // Sign calculates an ECDSA signature for: 1381 // keccack256("\x17Energi Signed Message:\n" + len(message) + message). 1382 // 1383 // Note, the produced signature conforms to the secp256k1 curve R, S and V values, 1384 // where the V value will be 27 or 28 for legacy reasons. 1385 // 1386 // The account associated with addr must be unlocked. 1387 // 1388 // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign 1389 func (s *PublicTransactionPoolAPI) Sign(addr common.Address, data hexutil.Bytes) (hexutil.Bytes, error) { 1390 // Look up the wallet containing the requested signer 1391 account := accounts.Account{Address: addr} 1392 1393 wallet, err := s.b.AccountManager().Find(account) 1394 if err != nil { 1395 return nil, err 1396 } 1397 // Sign the requested hash with the wallet 1398 signature, err := wallet.SignHash(account, signHash(data)) 1399 if err == nil { 1400 signature[64] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper 1401 } 1402 return signature, err 1403 } 1404 1405 // SignTransactionResult represents a RLP encoded signed transaction. 1406 type SignTransactionResult struct { 1407 Raw hexutil.Bytes `json:"raw"` 1408 Tx *types.Transaction `json:"tx"` 1409 } 1410 1411 // SignTransaction will sign the given transaction with the from account. 1412 // The node needs to have the private key of the account corresponding with 1413 // the given from address and it needs to be unlocked. 1414 func (s *PublicTransactionPoolAPI) SignTransaction(ctx context.Context, args SendTxArgs) (*SignTransactionResult, error) { 1415 if args.Gas == nil { 1416 return nil, fmt.Errorf("gas not specified") 1417 } 1418 if args.GasPrice == nil { 1419 return nil, fmt.Errorf("gasPrice not specified") 1420 } 1421 if args.Nonce == nil { 1422 return nil, fmt.Errorf("nonce not specified") 1423 } 1424 if err := args.setDefaults(ctx, s.b); err != nil { 1425 return nil, err 1426 } 1427 tx, err := s.sign(args.From, args.toTransaction()) 1428 if err != nil { 1429 return nil, err 1430 } 1431 data, err := rlp.EncodeToBytes(tx) 1432 if err != nil { 1433 return nil, err 1434 } 1435 return &SignTransactionResult{data, tx}, nil 1436 } 1437 1438 // PendingTransactions returns the transactions that are in the transaction pool 1439 // and have a from address that is one of the accounts this node manages. 1440 func (s *PublicTransactionPoolAPI) PendingTransactions() ([]*RPCTransaction, error) { 1441 pending, err := s.b.GetPoolTransactions() 1442 if err != nil { 1443 return nil, err 1444 } 1445 accounts := make(map[common.Address]struct{}) 1446 for _, wallet := range s.b.AccountManager().Wallets() { 1447 for _, account := range wallet.Accounts() { 1448 accounts[account.Address] = struct{}{} 1449 } 1450 } 1451 transactions := make([]*RPCTransaction, 0, len(pending)) 1452 for _, tx := range pending { 1453 var signer types.Signer = types.HomesteadSigner{} 1454 if tx.Protected() { 1455 signer = types.NewEIP155Signer(tx.ChainId()) 1456 } 1457 from, _ := types.Sender(signer, tx) 1458 if _, exists := accounts[from]; exists { 1459 transactions = append(transactions, newRPCPendingTransaction(tx)) 1460 } 1461 } 1462 return transactions, nil 1463 } 1464 1465 // Resend accepts an existing transaction and a new gas price and limit. It will remove 1466 // the given transaction from the pool and reinsert it with the new gas price and limit. 1467 func (s *PublicTransactionPoolAPI) Resend(ctx context.Context, sendArgs SendTxArgs, gasPrice *hexutil.Big, gasLimit *hexutil.Uint64) (common.Hash, error) { 1468 if sendArgs.Nonce == nil { 1469 return common.Hash{}, fmt.Errorf("missing transaction nonce in transaction spec") 1470 } 1471 if err := sendArgs.setDefaults(ctx, s.b); err != nil { 1472 return common.Hash{}, err 1473 } 1474 matchTx := sendArgs.toTransaction() 1475 pending, err := s.b.GetPoolTransactions() 1476 if err != nil { 1477 return common.Hash{}, err 1478 } 1479 1480 for _, p := range pending { 1481 var signer types.Signer = types.HomesteadSigner{} 1482 if p.Protected() { 1483 signer = types.NewEIP155Signer(p.ChainId()) 1484 } 1485 wantSigHash := signer.Hash(matchTx) 1486 1487 if pFrom, err := types.Sender(signer, p); err == nil && pFrom == sendArgs.From && signer.Hash(p) == wantSigHash { 1488 // Match. Re-sign and send the transaction. 1489 if gasPrice != nil && (*big.Int)(gasPrice).Sign() != 0 { 1490 sendArgs.GasPrice = gasPrice 1491 } 1492 if gasLimit != nil && *gasLimit != 0 { 1493 sendArgs.Gas = gasLimit 1494 } 1495 signedTx, err := s.sign(sendArgs.From, sendArgs.toTransaction()) 1496 if err != nil { 1497 return common.Hash{}, err 1498 } 1499 if err = s.b.SendTx(ctx, signedTx); err != nil { 1500 return common.Hash{}, err 1501 } 1502 return signedTx.Hash(), nil 1503 } 1504 } 1505 1506 return common.Hash{}, fmt.Errorf("Transaction %#x not found", matchTx.Hash()) 1507 } 1508 1509 // PublicDebugAPI is the collection of Ethereum APIs exposed over the public 1510 // debugging endpoint. 1511 type PublicDebugAPI struct { 1512 b Backend 1513 } 1514 1515 // NewPublicDebugAPI creates a new API definition for the public debug methods 1516 // of the Ethereum service. 1517 func NewPublicDebugAPI(b Backend) *PublicDebugAPI { 1518 return &PublicDebugAPI{b: b} 1519 } 1520 1521 // GetBlockRlp retrieves the RLP encoded for of a single block. 1522 func (api *PublicDebugAPI) GetBlockRlp(ctx context.Context, number uint64) (string, error) { 1523 block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number)) 1524 if block == nil { 1525 return "", fmt.Errorf("block #%d not found", number) 1526 } 1527 encoded, err := rlp.EncodeToBytes(block) 1528 if err != nil { 1529 return "", err 1530 } 1531 return fmt.Sprintf("%x", encoded), nil 1532 } 1533 1534 // PrintBlock retrieves a block and returns its pretty printed form. 1535 func (api *PublicDebugAPI) PrintBlock(ctx context.Context, number uint64) (string, error) { 1536 block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number)) 1537 if block == nil { 1538 return "", fmt.Errorf("block #%d not found", number) 1539 } 1540 return spew.Sdump(block), nil 1541 } 1542 1543 // SeedHash retrieves the seed hash of a block. 1544 func (api *PublicDebugAPI) SeedHash(ctx context.Context, number uint64) (string, error) { 1545 block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number)) 1546 if block == nil { 1547 return "", fmt.Errorf("block #%d not found", number) 1548 } 1549 return fmt.Sprintf("0x%x", ethash.SeedHash(number)), nil 1550 } 1551 1552 // PrivateDebugAPI is the collection of Ethereum APIs exposed over the private 1553 // debugging endpoint. 1554 type PrivateDebugAPI struct { 1555 b Backend 1556 } 1557 1558 // NewPrivateDebugAPI creates a new API definition for the private debug methods 1559 // of the Ethereum service. 1560 func NewPrivateDebugAPI(b Backend) *PrivateDebugAPI { 1561 return &PrivateDebugAPI{b: b} 1562 } 1563 1564 // ChaindbProperty returns leveldb properties of the chain database. 1565 func (api *PrivateDebugAPI) ChaindbProperty(property string) (string, error) { 1566 ldb, ok := api.b.ChainDb().(interface { 1567 LDB() *leveldb.DB 1568 }) 1569 if !ok { 1570 return "", fmt.Errorf("chaindbProperty does not work for memory databases") 1571 } 1572 if property == "" { 1573 property = "leveldb.stats" 1574 } else if !strings.HasPrefix(property, "leveldb.") { 1575 property = "leveldb." + property 1576 } 1577 return ldb.LDB().GetProperty(property) 1578 } 1579 1580 func (api *PrivateDebugAPI) ChaindbCompact() error { 1581 ldb, ok := api.b.ChainDb().(interface { 1582 LDB() *leveldb.DB 1583 }) 1584 if !ok { 1585 return fmt.Errorf("chaindbCompact does not work for memory databases") 1586 } 1587 for b := byte(0); b < 255; b++ { 1588 log.Info("Compacting chain database", "range", fmt.Sprintf("0x%0.2X-0x%0.2X", b, b+1)) 1589 err := ldb.LDB().CompactRange(util.Range{Start: []byte{b}, Limit: []byte{b + 1}}) 1590 if err != nil { 1591 log.Error("Database compaction failed", "err", err) 1592 return err 1593 } 1594 } 1595 return nil 1596 } 1597 1598 // SetHead rewinds the head of the blockchain to a previous block. 1599 func (api *PrivateDebugAPI) SetHead(number hexutil.Uint64) { 1600 api.b.SetHead(uint64(number)) 1601 } 1602 1603 // PublicNetAPI offers network related RPC methods 1604 type PublicNetAPI struct { 1605 net *p2p.Server 1606 networkVersion uint64 1607 } 1608 1609 // NewPublicNetAPI creates a new net API instance. 1610 func NewPublicNetAPI(net *p2p.Server, networkVersion uint64) *PublicNetAPI { 1611 return &PublicNetAPI{net, networkVersion} 1612 } 1613 1614 // Listening returns an indication if the node is listening for network connections. 1615 func (s *PublicNetAPI) Listening() bool { 1616 return true // always listening 1617 } 1618 1619 // PeerCount returns the number of connected peers 1620 func (s *PublicNetAPI) PeerCount() hexutil.Uint { 1621 return hexutil.Uint(s.net.PeerCount()) 1622 } 1623 1624 // Version returns the current ethereum protocol version. 1625 func (s *PublicNetAPI) Version() string { 1626 return fmt.Sprintf("%d", s.networkVersion) 1627 }