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