Commit cf71f5cd authored by Felix Lange's avatar Felix Lange

rpc: remove HexNumber, replace all uses with hexutil types

This change couldn't be automated because HexNumber was used for numbers
of all sizes.
parent adab2e16
...@@ -31,6 +31,7 @@ import ( ...@@ -31,6 +31,7 @@ import (
"github.com/ethereum/ethash" "github.com/ethereum/ethash"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/state" "github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/types"
...@@ -69,8 +70,8 @@ func (s *PublicEthereumAPI) Coinbase() (common.Address, error) { ...@@ -69,8 +70,8 @@ func (s *PublicEthereumAPI) Coinbase() (common.Address, error) {
} }
// Hashrate returns the POW hashrate // Hashrate returns the POW hashrate
func (s *PublicEthereumAPI) Hashrate() *rpc.HexNumber { func (s *PublicEthereumAPI) Hashrate() hexutil.Uint64 {
return rpc.NewHexNumber(s.e.Miner().HashRate()) return hexutil.Uint64(s.e.Miner().HashRate())
} }
// PublicMinerAPI provides an API to control the miner. // PublicMinerAPI provides an API to control the miner.
...@@ -95,8 +96,8 @@ func (s *PublicMinerAPI) Mining() bool { ...@@ -95,8 +96,8 @@ func (s *PublicMinerAPI) Mining() bool {
// SubmitWork can be used by external miner to submit their POW solution. It returns an indication if the work was // SubmitWork can be used by external miner to submit their POW solution. It returns an indication if the work was
// accepted. Note, this is not an indication if the provided work was valid! // accepted. Note, this is not an indication if the provided work was valid!
func (s *PublicMinerAPI) SubmitWork(nonce rpc.HexNumber, solution, digest common.Hash) bool { func (s *PublicMinerAPI) SubmitWork(nonce hexutil.Uint64, solution, digest common.Hash) bool {
return s.agent.SubmitWork(nonce.Uint64(), digest, solution) return s.agent.SubmitWork(uint64(nonce), digest, solution)
} }
// GetWork returns a work package for external miner. The work package consists of 3 strings // GetWork returns a work package for external miner. The work package consists of 3 strings
...@@ -119,8 +120,8 @@ func (s *PublicMinerAPI) GetWork() (work [3]string, err error) { ...@@ -119,8 +120,8 @@ func (s *PublicMinerAPI) GetWork() (work [3]string, err error) {
// SubmitHashrate can be used for remote miners to submit their hash rate. This enables the node to report the combined // SubmitHashrate can be used for remote miners to submit their hash rate. This enables the node to report the combined
// hash rate of all miners which submit work through this node. It accepts the miner hash rate and an identifier which // hash rate of all miners which submit work through this node. It accepts the miner hash rate and an identifier which
// must be unique between nodes. // must be unique between nodes.
func (s *PublicMinerAPI) SubmitHashrate(hashrate rpc.HexNumber, id common.Hash) bool { func (s *PublicMinerAPI) SubmitHashrate(hashrate hexutil.Uint64, id common.Hash) bool {
s.agent.SubmitHashrate(id, hashrate.Uint64()) s.agent.SubmitHashrate(id, uint64(hashrate))
return true return true
} }
...@@ -137,18 +138,15 @@ func NewPrivateMinerAPI(e *Ethereum) *PrivateMinerAPI { ...@@ -137,18 +138,15 @@ func NewPrivateMinerAPI(e *Ethereum) *PrivateMinerAPI {
// Start the miner with the given number of threads. If threads is nil the number of // Start the miner with the given number of threads. If threads is nil the number of
// workers started is equal to the number of logical CPU's that are usable by this process. // workers started is equal to the number of logical CPU's that are usable by this process.
func (s *PrivateMinerAPI) Start(threads *rpc.HexNumber) (bool, error) { func (s *PrivateMinerAPI) Start(threads *hexutil.Uint) (bool, error) {
s.e.StartAutoDAG() s.e.StartAutoDAG()
var err error
if threads == nil { if threads == nil {
threads = rpc.NewHexNumber(runtime.NumCPU()) err = s.e.StartMining(runtime.NumCPU())
} } else {
err = s.e.StartMining(int(*threads))
err := s.e.StartMining(threads.Int())
if err == nil {
return true, nil
} }
return false, err return err == nil, err
} }
// Stop the miner // Stop the miner
...@@ -166,8 +164,8 @@ func (s *PrivateMinerAPI) SetExtra(extra string) (bool, error) { ...@@ -166,8 +164,8 @@ func (s *PrivateMinerAPI) SetExtra(extra string) (bool, error) {
} }
// SetGasPrice sets the minimum accepted gas price for the miner. // SetGasPrice sets the minimum accepted gas price for the miner.
func (s *PrivateMinerAPI) SetGasPrice(gasPrice rpc.HexNumber) bool { func (s *PrivateMinerAPI) SetGasPrice(gasPrice hexutil.Big) bool {
s.e.Miner().SetGasPrice(gasPrice.BigInt()) s.e.Miner().SetGasPrice((*big.Int)(&gasPrice))
return true return true
} }
......
...@@ -21,6 +21,7 @@ import ( ...@@ -21,6 +21,7 @@ import (
"github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/internal/ethapi" "github.com/ethereum/go-ethereum/internal/ethapi"
"github.com/ethereum/go-ethereum/rlp" "github.com/ethereum/go-ethereum/rlp"
...@@ -86,13 +87,13 @@ func toCallArgs(msg ethereum.CallMsg) ethapi.CallArgs { ...@@ -86,13 +87,13 @@ func toCallArgs(msg ethereum.CallMsg) ethapi.CallArgs {
Data: common.ToHex(msg.Data), Data: common.ToHex(msg.Data),
} }
if msg.Gas != nil { if msg.Gas != nil {
args.Gas = *rpc.NewHexNumber(msg.Gas) args.Gas = hexutil.Big(*msg.Gas)
} }
if msg.GasPrice != nil { if msg.GasPrice != nil {
args.GasPrice = *rpc.NewHexNumber(msg.GasPrice) args.GasPrice = hexutil.Big(*msg.GasPrice)
} }
if msg.Value != nil { if msg.Value != nil {
args.Value = *rpc.NewHexNumber(msg.Value) args.Value = hexutil.Big(*msg.Value)
} }
return args return args
} }
...@@ -106,9 +107,12 @@ func toBlockNumber(num *big.Int) rpc.BlockNumber { ...@@ -106,9 +107,12 @@ func toBlockNumber(num *big.Int) rpc.BlockNumber {
// PendingAccountNonce implements bind.ContractTransactor retrieving the current // PendingAccountNonce implements bind.ContractTransactor retrieving the current
// pending nonce associated with an account. // pending nonce associated with an account.
func (b *ContractBackend) PendingNonceAt(ctx context.Context, account common.Address) (uint64, error) { func (b *ContractBackend) PendingNonceAt(ctx context.Context, account common.Address) (nonce uint64, err error) {
out, err := b.txapi.GetTransactionCount(ctx, account, rpc.PendingBlockNumber) out, err := b.txapi.GetTransactionCount(ctx, account, rpc.PendingBlockNumber)
return out.Uint64(), err if out != nil {
nonce = uint64(*out)
}
return nonce, err
} }
// SuggestGasPrice implements bind.ContractTransactor retrieving the currently // SuggestGasPrice implements bind.ContractTransactor retrieving the currently
...@@ -124,7 +128,7 @@ func (b *ContractBackend) SuggestGasPrice(ctx context.Context) (*big.Int, error) ...@@ -124,7 +128,7 @@ func (b *ContractBackend) SuggestGasPrice(ctx context.Context) (*big.Int, error)
// should provide a basis for setting a reasonable default. // should provide a basis for setting a reasonable default.
func (b *ContractBackend) EstimateGas(ctx context.Context, msg ethereum.CallMsg) (*big.Int, error) { func (b *ContractBackend) EstimateGas(ctx context.Context, msg ethereum.CallMsg) (*big.Int, error) {
out, err := b.bcapi.EstimateGas(ctx, toCallArgs(msg)) out, err := b.bcapi.EstimateGas(ctx, toCallArgs(msg))
return out.BigInt(), err return out.ToInt(), err
} }
// SendTransaction implements bind.ContractTransactor injects the transaction // SendTransaction implements bind.ContractTransactor injects the transaction
......
This diff is collapsed.
...@@ -26,6 +26,7 @@ import ( ...@@ -26,6 +26,7 @@ import (
"github.com/ethereum/go-ethereum/accounts" "github.com/ethereum/go-ethereum/accounts"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/compiler" "github.com/ethereum/go-ethereum/common/compiler"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/eth" "github.com/ethereum/go-ethereum/eth"
...@@ -135,8 +136,8 @@ func (s *LightDummyAPI) Coinbase() (common.Address, error) { ...@@ -135,8 +136,8 @@ func (s *LightDummyAPI) Coinbase() (common.Address, error) {
} }
// Hashrate returns the POW hashrate // Hashrate returns the POW hashrate
func (s *LightDummyAPI) Hashrate() *rpc.HexNumber { func (s *LightDummyAPI) Hashrate() hexutil.Uint {
return rpc.NewHexNumber(0) return 0
} }
// Mining returns an indication if this node is currently mining. // Mining returns an indication if this node is currently mining.
......
...@@ -25,7 +25,6 @@ import ( ...@@ -25,7 +25,6 @@ import (
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/p2p" "github.com/ethereum/go-ethereum/p2p"
"github.com/ethereum/go-ethereum/p2p/discover" "github.com/ethereum/go-ethereum/p2p/discover"
"github.com/ethereum/go-ethereum/rpc"
"github.com/rcrowley/go-metrics" "github.com/rcrowley/go-metrics"
) )
...@@ -75,7 +74,7 @@ func (api *PrivateAdminAPI) RemovePeer(url string) (bool, error) { ...@@ -75,7 +74,7 @@ func (api *PrivateAdminAPI) RemovePeer(url string) (bool, error) {
} }
// StartRPC starts the HTTP RPC API server. // StartRPC starts the HTTP RPC API server.
func (api *PrivateAdminAPI) StartRPC(host *string, port *rpc.HexNumber, cors *string, apis *string) (bool, error) { func (api *PrivateAdminAPI) StartRPC(host *string, port *int, cors *string, apis *string) (bool, error) {
api.node.lock.Lock() api.node.lock.Lock()
defer api.node.lock.Unlock() defer api.node.lock.Unlock()
...@@ -91,7 +90,7 @@ func (api *PrivateAdminAPI) StartRPC(host *string, port *rpc.HexNumber, cors *st ...@@ -91,7 +90,7 @@ func (api *PrivateAdminAPI) StartRPC(host *string, port *rpc.HexNumber, cors *st
host = &h host = &h
} }
if port == nil { if port == nil {
port = rpc.NewHexNumber(api.node.config.HTTPPort) port = &api.node.config.HTTPPort
} }
if cors == nil { if cors == nil {
cors = &api.node.config.HTTPCors cors = &api.node.config.HTTPCors
...@@ -105,7 +104,7 @@ func (api *PrivateAdminAPI) StartRPC(host *string, port *rpc.HexNumber, cors *st ...@@ -105,7 +104,7 @@ func (api *PrivateAdminAPI) StartRPC(host *string, port *rpc.HexNumber, cors *st
} }
} }
if err := api.node.startHTTP(fmt.Sprintf("%s:%d", *host, port.Int()), api.node.rpcAPIs, modules, *cors); err != nil { if err := api.node.startHTTP(fmt.Sprintf("%s:%d", *host, port), api.node.rpcAPIs, modules, *cors); err != nil {
return false, err return false, err
} }
return true, nil return true, nil
...@@ -124,7 +123,7 @@ func (api *PrivateAdminAPI) StopRPC() (bool, error) { ...@@ -124,7 +123,7 @@ func (api *PrivateAdminAPI) StopRPC() (bool, error) {
} }
// StartWS starts the websocket RPC API server. // StartWS starts the websocket RPC API server.
func (api *PrivateAdminAPI) StartWS(host *string, port *rpc.HexNumber, allowedOrigins *string, apis *string) (bool, error) { func (api *PrivateAdminAPI) StartWS(host *string, port *int, allowedOrigins *string, apis *string) (bool, error) {
api.node.lock.Lock() api.node.lock.Lock()
defer api.node.lock.Unlock() defer api.node.lock.Unlock()
...@@ -140,7 +139,7 @@ func (api *PrivateAdminAPI) StartWS(host *string, port *rpc.HexNumber, allowedOr ...@@ -140,7 +139,7 @@ func (api *PrivateAdminAPI) StartWS(host *string, port *rpc.HexNumber, allowedOr
host = &h host = &h
} }
if port == nil { if port == nil {
port = rpc.NewHexNumber(api.node.config.WSPort) port = &api.node.config.WSPort
} }
if allowedOrigins == nil { if allowedOrigins == nil {
allowedOrigins = &api.node.config.WSOrigins allowedOrigins = &api.node.config.WSOrigins
...@@ -154,7 +153,7 @@ func (api *PrivateAdminAPI) StartWS(host *string, port *rpc.HexNumber, allowedOr ...@@ -154,7 +153,7 @@ func (api *PrivateAdminAPI) StartWS(host *string, port *rpc.HexNumber, allowedOr
} }
} }
if err := api.node.startWS(fmt.Sprintf("%s:%d", *host, port.Int()), api.node.rpcAPIs, modules, *allowedOrigins); err != nil { if err := api.node.startWS(fmt.Sprintf("%s:%d", *host, *port), api.node.rpcAPIs, modules, *allowedOrigins); err != nil {
return false, err return false, err
} }
return true, nil return true, nil
......
...@@ -257,8 +257,8 @@ func parseBatchRequest(incomingMsg json.RawMessage) ([]rpcRequest, bool, Error) ...@@ -257,8 +257,8 @@ func parseBatchRequest(incomingMsg json.RawMessage) ([]rpcRequest, bool, Error)
return requests, true, nil return requests, true, nil
} }
// ParseRequestArguments tries to parse the given params (json.RawMessage) with the given types. It returns the parsed // ParseRequestArguments tries to parse the given params (json.RawMessage) with the given
// values or an error when the parsing failed. // types. It returns the parsed values or an error when the parsing failed.
func (c *jsonCodec) ParseRequestArguments(argTypes []reflect.Type, params interface{}) ([]reflect.Value, Error) { func (c *jsonCodec) ParseRequestArguments(argTypes []reflect.Type, params interface{}) ([]reflect.Value, Error) {
if args, ok := params.(json.RawMessage); !ok { if args, ok := params.(json.RawMessage); !ok {
return nil, &invalidParamsError{"Invalid params supplied"} return nil, &invalidParamsError{"Invalid params supplied"}
......
...@@ -121,91 +121,6 @@ type ServerCodec interface { ...@@ -121,91 +121,6 @@ type ServerCodec interface {
Closed() <-chan interface{} Closed() <-chan interface{}
} }
// HexNumber serializes a number to hex format using the "%#x" format
type HexNumber big.Int
// NewHexNumber creates a new hex number instance which will serialize the given val with `%#x` on marshal.
func NewHexNumber(val interface{}) *HexNumber {
if val == nil {
return nil // note, this doesn't catch nil pointers, only passing nil directly!
}
if v, ok := val.(*big.Int); ok {
if v != nil {
return (*HexNumber)(new(big.Int).Set(v))
}
return nil
}
rval := reflect.ValueOf(val)
var unsigned uint64
utype := reflect.TypeOf(unsigned)
if t := rval.Type(); t.ConvertibleTo(utype) {
hn := new(big.Int).SetUint64(rval.Convert(utype).Uint())
return (*HexNumber)(hn)
}
var signed int64
stype := reflect.TypeOf(signed)
if t := rval.Type(); t.ConvertibleTo(stype) {
hn := new(big.Int).SetInt64(rval.Convert(stype).Int())
return (*HexNumber)(hn)
}
return nil
}
func (h *HexNumber) UnmarshalJSON(input []byte) error {
length := len(input)
if length >= 2 && input[0] == '"' && input[length-1] == '"' {
input = input[1 : length-1]
}
hn := (*big.Int)(h)
if _, ok := hn.SetString(string(input), 0); ok {
return nil
}
return fmt.Errorf("Unable to parse number")
}
// MarshalJSON serialize the hex number instance to a hex representation.
func (h *HexNumber) MarshalJSON() ([]byte, error) {
if h != nil {
hn := (*big.Int)(h)
if hn.BitLen() == 0 {
return []byte(`"0x0"`), nil
}
return []byte(fmt.Sprintf(`"0x%x"`, hn)), nil
}
return nil, nil
}
func (h *HexNumber) Int() int {
hn := (*big.Int)(h)
return int(hn.Int64())
}
func (h *HexNumber) Int64() int64 {
hn := (*big.Int)(h)
return hn.Int64()
}
func (h *HexNumber) Uint() uint {
hn := (*big.Int)(h)
return uint(hn.Uint64())
}
func (h *HexNumber) Uint64() uint64 {
hn := (*big.Int)(h)
return hn.Uint64()
}
func (h *HexNumber) BigInt() *big.Int {
return (*big.Int)(h)
}
var ( var (
pendingBlockNumber = big.NewInt(-2) pendingBlockNumber = big.NewInt(-2)
latestBlockNumber = big.NewInt(-1) latestBlockNumber = big.NewInt(-1)
......
// Copyright 2015 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package rpc
import (
"bytes"
"encoding/json"
"math/big"
"testing"
)
func TestNewHexNumber(t *testing.T) {
tests := []interface{}{big.NewInt(123), int64(123), uint64(123), int8(123), uint8(123)}
for i, v := range tests {
hn := NewHexNumber(v)
if hn == nil {
t.Fatalf("Unable to create hex number instance for tests[%d]", i)
}
if hn.Int64() != 123 {
t.Fatalf("expected %d, got %d on value tests[%d]", 123, hn.Int64(), i)
}
}
failures := []interface{}{"", nil, []byte{1, 2, 3, 4}}
for i, v := range failures {
hn := NewHexNumber(v)
if hn != nil {
t.Fatalf("Creating a nex number instance of %T should fail (failures[%d])", failures[i], i)
}
}
}
func TestHexNumberUnmarshalJSON(t *testing.T) {
tests := []string{`"0x4d2"`, "1234", `"1234"`}
for i, v := range tests {
var hn HexNumber
if err := json.Unmarshal([]byte(v), &hn); err != nil {
t.Fatalf("Test %d failed - %s", i, err)
}
if hn.Int64() != 1234 {
t.Fatalf("Expected %d, got %d for test[%d]", 1234, hn.Int64(), i)
}
}
}
func TestHexNumberMarshalJSON(t *testing.T) {
hn := NewHexNumber(1234567890)
got, err := json.Marshal(hn)
if err != nil {
t.Fatalf("Unable to marshal hex number - %s", err)
}
exp := []byte(`"0x499602d2"`)
if bytes.Compare(exp, got) != 0 {
t.Fatalf("Invalid json.Marshal, expected '%s', got '%s'", exp, got)
}
}
...@@ -73,11 +73,11 @@ func (api *PublicWhisperAPI) Stop() error { ...@@ -73,11 +73,11 @@ func (api *PublicWhisperAPI) Stop() error {
} }
// Version returns the Whisper version this node offers. // Version returns the Whisper version this node offers.
func (api *PublicWhisperAPI) Version() (*rpc.HexNumber, error) { func (api *PublicWhisperAPI) Version() (hexutil.Uint, error) {
if api.whisper == nil { if api.whisper == nil {
return rpc.NewHexNumber(0), whisperOffLineErr return 0, whisperOffLineErr
} }
return rpc.NewHexNumber(api.whisper.Version()), nil return hexutil.Uint(api.whisper.Version()), nil
} }
// MarkPeerTrusted marks specific peer trusted, which will allow it // MarkPeerTrusted marks specific peer trusted, which will allow it
......
...@@ -39,8 +39,8 @@ func TestBasic(t *testing.T) { ...@@ -39,8 +39,8 @@ func TestBasic(t *testing.T) {
t.Fatalf("failed generateFilter: %s.", err) t.Fatalf("failed generateFilter: %s.", err)
} }
if ver.Uint64() != whisperv5.ProtocolVersion { if uint64(ver) != whisperv5.ProtocolVersion {
t.Fatalf("wrong version: %d.", ver.Uint64()) t.Fatalf("wrong version: %d.", ver)
} }
mail := api.GetFilterChanges(1) mail := api.GetFilterChanges(1)
......
...@@ -23,8 +23,8 @@ import ( ...@@ -23,8 +23,8 @@ import (
"time" "time"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/rpc"
) )
// PublicWhisperAPI provides the whisper RPC service. // PublicWhisperAPI provides the whisper RPC service.
...@@ -32,7 +32,7 @@ type PublicWhisperAPI struct { ...@@ -32,7 +32,7 @@ type PublicWhisperAPI struct {
w *Whisper w *Whisper
messagesMu sync.RWMutex messagesMu sync.RWMutex
messages map[int]*whisperFilter messages map[hexutil.Uint]*whisperFilter
} }
type whisperOfflineError struct{} type whisperOfflineError struct{}
...@@ -46,15 +46,15 @@ var whisperOffLineErr = new(whisperOfflineError) ...@@ -46,15 +46,15 @@ var whisperOffLineErr = new(whisperOfflineError)
// NewPublicWhisperAPI create a new RPC whisper service. // NewPublicWhisperAPI create a new RPC whisper service.
func NewPublicWhisperAPI(w *Whisper) *PublicWhisperAPI { func NewPublicWhisperAPI(w *Whisper) *PublicWhisperAPI {
return &PublicWhisperAPI{w: w, messages: make(map[int]*whisperFilter)} return &PublicWhisperAPI{w: w, messages: make(map[hexutil.Uint]*whisperFilter)}
} }
// Version returns the Whisper version this node offers. // Version returns the Whisper version this node offers.
func (s *PublicWhisperAPI) Version() (*rpc.HexNumber, error) { func (s *PublicWhisperAPI) Version() (hexutil.Uint, error) {
if s.w == nil { if s.w == nil {
return rpc.NewHexNumber(0), whisperOffLineErr return 0, whisperOffLineErr
} }
return rpc.NewHexNumber(s.w.Version()), nil return hexutil.Uint(s.w.Version()), nil
} }
// HasIdentity checks if the the whisper node is configured with the private key // HasIdentity checks if the the whisper node is configured with the private key
...@@ -84,12 +84,12 @@ type NewFilterArgs struct { ...@@ -84,12 +84,12 @@ type NewFilterArgs struct {
} }
// NewWhisperFilter creates and registers a new message filter to watch for inbound whisper messages. // NewWhisperFilter creates and registers a new message filter to watch for inbound whisper messages.
func (s *PublicWhisperAPI) NewFilter(args NewFilterArgs) (*rpc.HexNumber, error) { func (s *PublicWhisperAPI) NewFilter(args NewFilterArgs) (hexutil.Uint, error) {
if s.w == nil { if s.w == nil {
return nil, whisperOffLineErr return 0, whisperOffLineErr
} }
var id int var id hexutil.Uint
filter := Filter{ filter := Filter{
To: crypto.ToECDSAPub(common.FromHex(args.To)), To: crypto.ToECDSAPub(common.FromHex(args.To)),
From: crypto.ToECDSAPub(common.FromHex(args.From)), From: crypto.ToECDSAPub(common.FromHex(args.From)),
...@@ -103,23 +103,22 @@ func (s *PublicWhisperAPI) NewFilter(args NewFilterArgs) (*rpc.HexNumber, error) ...@@ -103,23 +103,22 @@ func (s *PublicWhisperAPI) NewFilter(args NewFilterArgs) (*rpc.HexNumber, error)
} }
}, },
} }
id = hexutil.Uint(s.w.Watch(filter))
id = s.w.Watch(filter)
s.messagesMu.Lock() s.messagesMu.Lock()
s.messages[id] = newWhisperFilter(id, s.w) s.messages[id] = newWhisperFilter(id, s.w)
s.messagesMu.Unlock() s.messagesMu.Unlock()
return rpc.NewHexNumber(id), nil return id, nil
} }
// GetFilterChanges retrieves all the new messages matched by a filter since the last retrieval. // GetFilterChanges retrieves all the new messages matched by a filter since the last retrieval.
func (s *PublicWhisperAPI) GetFilterChanges(filterId rpc.HexNumber) []WhisperMessage { func (s *PublicWhisperAPI) GetFilterChanges(filterId hexutil.Uint) []WhisperMessage {
s.messagesMu.RLock() s.messagesMu.RLock()
defer s.messagesMu.RUnlock() defer s.messagesMu.RUnlock()
if s.messages[filterId.Int()] != nil { if s.messages[filterId] != nil {
if changes := s.messages[filterId.Int()].retrieve(); changes != nil { if changes := s.messages[filterId].retrieve(); changes != nil {
return changes return changes
} }
} }
...@@ -127,26 +126,26 @@ func (s *PublicWhisperAPI) GetFilterChanges(filterId rpc.HexNumber) []WhisperMes ...@@ -127,26 +126,26 @@ func (s *PublicWhisperAPI) GetFilterChanges(filterId rpc.HexNumber) []WhisperMes
} }
// UninstallFilter disables and removes an existing filter. // UninstallFilter disables and removes an existing filter.
func (s *PublicWhisperAPI) UninstallFilter(filterId rpc.HexNumber) bool { func (s *PublicWhisperAPI) UninstallFilter(filterId hexutil.Uint) bool {
s.messagesMu.Lock() s.messagesMu.Lock()
defer s.messagesMu.Unlock() defer s.messagesMu.Unlock()
if _, ok := s.messages[filterId.Int()]; ok { if _, ok := s.messages[filterId]; ok {
delete(s.messages, filterId.Int()) delete(s.messages, filterId)
return true return true
} }
return false return false
} }
// GetMessages retrieves all the known messages that match a specific filter. // GetMessages retrieves all the known messages that match a specific filter.
func (s *PublicWhisperAPI) GetMessages(filterId rpc.HexNumber) []WhisperMessage { func (s *PublicWhisperAPI) GetMessages(filterId hexutil.Uint) []WhisperMessage {
// Retrieve all the cached messages matching a specific, existing filter // Retrieve all the cached messages matching a specific, existing filter
s.messagesMu.RLock() s.messagesMu.RLock()
defer s.messagesMu.RUnlock() defer s.messagesMu.RUnlock()
var messages []*Message var messages []*Message
if s.messages[filterId.Int()] != nil { if s.messages[filterId] != nil {
messages = s.messages[filterId.Int()].messages() messages = s.messages[filterId].messages()
} }
return returnWhisperMessages(messages) return returnWhisperMessages(messages)
...@@ -217,12 +216,12 @@ type WhisperMessage struct { ...@@ -217,12 +216,12 @@ type WhisperMessage struct {
func (args *PostArgs) UnmarshalJSON(data []byte) (err error) { func (args *PostArgs) UnmarshalJSON(data []byte) (err error) {
var obj struct { var obj struct {
From string `json:"from"` From string `json:"from"`
To string `json:"to"` To string `json:"to"`
Topics []string `json:"topics"` Topics []string `json:"topics"`
Payload string `json:"payload"` Payload string `json:"payload"`
Priority rpc.HexNumber `json:"priority"` Priority hexutil.Uint64 `json:"priority"`
TTL rpc.HexNumber `json:"ttl"` TTL hexutil.Uint64 `json:"ttl"`
} }
if err := json.Unmarshal(data, &obj); err != nil { if err := json.Unmarshal(data, &obj); err != nil {
...@@ -232,8 +231,8 @@ func (args *PostArgs) UnmarshalJSON(data []byte) (err error) { ...@@ -232,8 +231,8 @@ func (args *PostArgs) UnmarshalJSON(data []byte) (err error) {
args.From = obj.From args.From = obj.From
args.To = obj.To args.To = obj.To
args.Payload = obj.Payload args.Payload = obj.Payload
args.Priority = obj.Priority.Int64() args.Priority = int64(obj.Priority) // TODO(gluk256): handle overflow
args.TTL = obj.TTL.Int64() args.TTL = int64(obj.TTL) // ... here too ...
// decode topic strings // decode topic strings
args.Topics = make([][]byte, len(obj.Topics)) args.Topics = make([][]byte, len(obj.Topics))
...@@ -328,8 +327,8 @@ func (args *NewFilterArgs) UnmarshalJSON(b []byte) (err error) { ...@@ -328,8 +327,8 @@ func (args *NewFilterArgs) UnmarshalJSON(b []byte) (err error) {
// whisperFilter is the message cache matching a specific filter, accumulating // whisperFilter is the message cache matching a specific filter, accumulating
// inbound messages until the are requested by the client. // inbound messages until the are requested by the client.
type whisperFilter struct { type whisperFilter struct {
id int // Filter identifier for old message retrieval id hexutil.Uint // Filter identifier for old message retrieval
ref *Whisper // Whisper reference for old message retrieval ref *Whisper // Whisper reference for old message retrieval
cache []WhisperMessage // Cache of messages not yet polled cache []WhisperMessage // Cache of messages not yet polled
skip map[common.Hash]struct{} // List of retrieved messages to avoid duplication skip map[common.Hash]struct{} // List of retrieved messages to avoid duplication
...@@ -348,7 +347,7 @@ func (w *whisperFilter) messages() []*Message { ...@@ -348,7 +347,7 @@ func (w *whisperFilter) messages() []*Message {
w.update = time.Now() w.update = time.Now()
w.skip = make(map[common.Hash]struct{}) w.skip = make(map[common.Hash]struct{})
messages := w.ref.Messages(w.id) messages := w.ref.Messages(int(w.id))
for _, message := range messages { for _, message := range messages {
w.skip[message.Hash] = struct{}{} w.skip[message.Hash] = struct{}{}
} }
...@@ -388,11 +387,10 @@ func (w *whisperFilter) activity() time.Time { ...@@ -388,11 +387,10 @@ func (w *whisperFilter) activity() time.Time {
} }
// newWhisperFilter creates a new serialized, poll based whisper topic filter. // newWhisperFilter creates a new serialized, poll based whisper topic filter.
func newWhisperFilter(id int, ref *Whisper) *whisperFilter { func newWhisperFilter(id hexutil.Uint, ref *Whisper) *whisperFilter {
return &whisperFilter{ return &whisperFilter{
id: id, id: id,
ref: ref, ref: ref,
update: time.Now(), update: time.Now(),
skip: make(map[common.Hash]struct{}), skip: make(map[common.Hash]struct{}),
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment