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