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