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