Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Support
Submit feedback
Contribute to GitLab
Sign in
Toggle navigation
N
nebula
Project
Project
Details
Activity
Releases
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Boards
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
exchain
nebula
Commits
f948f078
Commit
f948f078
authored
Oct 12, 2021
by
George Hotz
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
consensus/consensus.go is stock now
parent
b476b137
Changes
6
Hide whitespace changes
Inline
Side-by-side
Showing
6 changed files
with
681 additions
and
2 deletions
+681
-2
files_minigeth
files_minigeth
+14
-0
consensus.go
minigeth/consensus/consensus.go
+2
-2
fake_ethash.go
minigeth/consensus/ethash/fake_ethash.go
+5
-0
errors.go
minigeth/rpc/errors.go
+103
-0
json.go
minigeth/rpc/json.go
+342
-0
types.go
minigeth/rpc/types.go
+215
-0
No files found.
files_minigeth
View file @
f948f078
common/hexutil/hexutil.go
common/hexutil/json.go
common/math/big.go
common/math/integer.go
common/big.go
common/bytes.go
common/size.go
common/types.go
consensus/misc/eip1559.go
consensus/misc/gaslimit.go
consensus/consensus.go
rpc/errors.go
rpc/json.go
rpc/types.go
minigeth/consensus/consensus.go
View file @
f948f078
...
...
@@ -24,7 +24,7 @@ import (
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/params"
//
"github.com/ethereum/go-ethereum/rpc"
"github.com/ethereum/go-ethereum/rpc"
)
// ChainHeaderReader defines a small collection of methods needed to access the local
...
...
@@ -112,7 +112,7 @@ type Engine interface {
CalcDifficulty
(
chain
ChainHeaderReader
,
time
uint64
,
parent
*
types
.
Header
)
*
big
.
Int
// APIs returns the RPC APIs this consensus engine provides.
//
APIs(chain ChainHeaderReader) []rpc.API
APIs
(
chain
ChainHeaderReader
)
[]
rpc
.
API
// Close terminates any background threads maintained by the consensus engine.
Close
()
error
...
...
minigeth/consensus/ethash/fake_ethash.go
View file @
f948f078
...
...
@@ -10,6 +10,7 @@ import (
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/params"
"github.com/ethereum/go-ethereum/rpc"
)
type
Ethash
struct
{}
...
...
@@ -29,6 +30,10 @@ func (ethash *Ethash) Close() error {
return
nil
}
func
(
ethash
*
Ethash
)
APIs
(
chain
consensus
.
ChainHeaderReader
)
[]
rpc
.
API
{
return
make
([]
rpc
.
API
,
0
)
}
// Ethash proof-of-work protocol constants.
var
(
FrontierBlockReward
=
big
.
NewInt
(
5e+18
)
// Block reward in wei for successfully mining a block
...
...
minigeth/rpc/errors.go
0 → 100644
View file @
f948f078
// 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
"fmt"
// HTTPError is returned by client operations when the HTTP status code of the
// response is not a 2xx status.
type
HTTPError
struct
{
StatusCode
int
Status
string
Body
[]
byte
}
func
(
err
HTTPError
)
Error
()
string
{
if
len
(
err
.
Body
)
==
0
{
return
err
.
Status
}
return
fmt
.
Sprintf
(
"%v: %s"
,
err
.
Status
,
err
.
Body
)
}
// Error wraps RPC errors, which contain an error code in addition to the message.
type
Error
interface
{
Error
()
string
// returns the message
ErrorCode
()
int
// returns the code
}
// A DataError contains some data in addition to the error message.
type
DataError
interface
{
Error
()
string
// returns the message
ErrorData
()
interface
{}
// returns the error data
}
// Error types defined below are the built-in JSON-RPC errors.
var
(
_
Error
=
new
(
methodNotFoundError
)
_
Error
=
new
(
subscriptionNotFoundError
)
_
Error
=
new
(
parseError
)
_
Error
=
new
(
invalidRequestError
)
_
Error
=
new
(
invalidMessageError
)
_
Error
=
new
(
invalidParamsError
)
)
const
defaultErrorCode
=
-
32000
type
methodNotFoundError
struct
{
method
string
}
func
(
e
*
methodNotFoundError
)
ErrorCode
()
int
{
return
-
32601
}
func
(
e
*
methodNotFoundError
)
Error
()
string
{
return
fmt
.
Sprintf
(
"the method %s does not exist/is not available"
,
e
.
method
)
}
type
subscriptionNotFoundError
struct
{
namespace
,
subscription
string
}
func
(
e
*
subscriptionNotFoundError
)
ErrorCode
()
int
{
return
-
32601
}
func
(
e
*
subscriptionNotFoundError
)
Error
()
string
{
return
fmt
.
Sprintf
(
"no %q subscription in %s namespace"
,
e
.
subscription
,
e
.
namespace
)
}
// Invalid JSON was received by the server.
type
parseError
struct
{
message
string
}
func
(
e
*
parseError
)
ErrorCode
()
int
{
return
-
32700
}
func
(
e
*
parseError
)
Error
()
string
{
return
e
.
message
}
// received message isn't a valid request
type
invalidRequestError
struct
{
message
string
}
func
(
e
*
invalidRequestError
)
ErrorCode
()
int
{
return
-
32600
}
func
(
e
*
invalidRequestError
)
Error
()
string
{
return
e
.
message
}
// received message is invalid
type
invalidMessageError
struct
{
message
string
}
func
(
e
*
invalidMessageError
)
ErrorCode
()
int
{
return
-
32700
}
func
(
e
*
invalidMessageError
)
Error
()
string
{
return
e
.
message
}
// unable to decode supplied params, or an invalid number of parameters
type
invalidParamsError
struct
{
message
string
}
func
(
e
*
invalidParamsError
)
ErrorCode
()
int
{
return
-
32602
}
func
(
e
*
invalidParamsError
)
Error
()
string
{
return
e
.
message
}
minigeth/rpc/json.go
0 → 100644
View file @
f948f078
// 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"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"reflect"
"strings"
"sync"
"time"
)
const
(
vsn
=
"2.0"
serviceMethodSeparator
=
"_"
subscribeMethodSuffix
=
"_subscribe"
unsubscribeMethodSuffix
=
"_unsubscribe"
notificationMethodSuffix
=
"_subscription"
defaultWriteTimeout
=
10
*
time
.
Second
// used if context has no deadline
)
var
null
=
json
.
RawMessage
(
"null"
)
type
subscriptionResult
struct
{
ID
string
`json:"subscription"`
Result
json
.
RawMessage
`json:"result,omitempty"`
}
// A value of this type can a JSON-RPC request, notification, successful response or
// error response. Which one it is depends on the fields.
type
jsonrpcMessage
struct
{
Version
string
`json:"jsonrpc,omitempty"`
ID
json
.
RawMessage
`json:"id,omitempty"`
Method
string
`json:"method,omitempty"`
Params
json
.
RawMessage
`json:"params,omitempty"`
Error
*
jsonError
`json:"error,omitempty"`
Result
json
.
RawMessage
`json:"result,omitempty"`
}
func
(
msg
*
jsonrpcMessage
)
isNotification
()
bool
{
return
msg
.
ID
==
nil
&&
msg
.
Method
!=
""
}
func
(
msg
*
jsonrpcMessage
)
isCall
()
bool
{
return
msg
.
hasValidID
()
&&
msg
.
Method
!=
""
}
func
(
msg
*
jsonrpcMessage
)
isResponse
()
bool
{
return
msg
.
hasValidID
()
&&
msg
.
Method
==
""
&&
msg
.
Params
==
nil
&&
(
msg
.
Result
!=
nil
||
msg
.
Error
!=
nil
)
}
func
(
msg
*
jsonrpcMessage
)
hasValidID
()
bool
{
return
len
(
msg
.
ID
)
>
0
&&
msg
.
ID
[
0
]
!=
'{'
&&
msg
.
ID
[
0
]
!=
'['
}
func
(
msg
*
jsonrpcMessage
)
isSubscribe
()
bool
{
return
strings
.
HasSuffix
(
msg
.
Method
,
subscribeMethodSuffix
)
}
func
(
msg
*
jsonrpcMessage
)
isUnsubscribe
()
bool
{
return
strings
.
HasSuffix
(
msg
.
Method
,
unsubscribeMethodSuffix
)
}
func
(
msg
*
jsonrpcMessage
)
namespace
()
string
{
elem
:=
strings
.
SplitN
(
msg
.
Method
,
serviceMethodSeparator
,
2
)
return
elem
[
0
]
}
func
(
msg
*
jsonrpcMessage
)
String
()
string
{
b
,
_
:=
json
.
Marshal
(
msg
)
return
string
(
b
)
}
func
(
msg
*
jsonrpcMessage
)
errorResponse
(
err
error
)
*
jsonrpcMessage
{
resp
:=
errorMessage
(
err
)
resp
.
ID
=
msg
.
ID
return
resp
}
func
(
msg
*
jsonrpcMessage
)
response
(
result
interface
{})
*
jsonrpcMessage
{
enc
,
err
:=
json
.
Marshal
(
result
)
if
err
!=
nil
{
// TODO: wrap with 'internal server error'
return
msg
.
errorResponse
(
err
)
}
return
&
jsonrpcMessage
{
Version
:
vsn
,
ID
:
msg
.
ID
,
Result
:
enc
}
}
func
errorMessage
(
err
error
)
*
jsonrpcMessage
{
msg
:=
&
jsonrpcMessage
{
Version
:
vsn
,
ID
:
null
,
Error
:
&
jsonError
{
Code
:
defaultErrorCode
,
Message
:
err
.
Error
(),
}}
ec
,
ok
:=
err
.
(
Error
)
if
ok
{
msg
.
Error
.
Code
=
ec
.
ErrorCode
()
}
de
,
ok
:=
err
.
(
DataError
)
if
ok
{
msg
.
Error
.
Data
=
de
.
ErrorData
()
}
return
msg
}
type
jsonError
struct
{
Code
int
`json:"code"`
Message
string
`json:"message"`
Data
interface
{}
`json:"data,omitempty"`
}
func
(
err
*
jsonError
)
Error
()
string
{
if
err
.
Message
==
""
{
return
fmt
.
Sprintf
(
"json-rpc error %d"
,
err
.
Code
)
}
return
err
.
Message
}
func
(
err
*
jsonError
)
ErrorCode
()
int
{
return
err
.
Code
}
func
(
err
*
jsonError
)
ErrorData
()
interface
{}
{
return
err
.
Data
}
// Conn is a subset of the methods of net.Conn which are sufficient for ServerCodec.
type
Conn
interface
{
io
.
ReadWriteCloser
SetWriteDeadline
(
time
.
Time
)
error
}
type
deadlineCloser
interface
{
io
.
Closer
SetWriteDeadline
(
time
.
Time
)
error
}
// ConnRemoteAddr wraps the RemoteAddr operation, which returns a description
// of the peer address of a connection. If a Conn also implements ConnRemoteAddr, this
// description is used in log messages.
type
ConnRemoteAddr
interface
{
RemoteAddr
()
string
}
// jsonCodec reads and writes JSON-RPC messages to the underlying connection. It also has
// support for parsing arguments and serializing (result) objects.
type
jsonCodec
struct
{
remote
string
closer
sync
.
Once
// close closed channel once
closeCh
chan
interface
{}
// closed on Close
decode
func
(
v
interface
{})
error
// decoder to allow multiple transports
encMu
sync
.
Mutex
// guards the encoder
encode
func
(
v
interface
{})
error
// encoder to allow multiple transports
conn
deadlineCloser
}
// NewFuncCodec creates a codec which uses the given functions to read and write. If conn
// implements ConnRemoteAddr, log messages will use it to include the remote address of
// the connection.
func
NewFuncCodec
(
conn
deadlineCloser
,
encode
,
decode
func
(
v
interface
{})
error
)
ServerCodec
{
codec
:=
&
jsonCodec
{
closeCh
:
make
(
chan
interface
{}),
encode
:
encode
,
decode
:
decode
,
conn
:
conn
,
}
if
ra
,
ok
:=
conn
.
(
ConnRemoteAddr
);
ok
{
codec
.
remote
=
ra
.
RemoteAddr
()
}
return
codec
}
// NewCodec creates a codec on the given connection. If conn implements ConnRemoteAddr, log
// messages will use it to include the remote address of the connection.
func
NewCodec
(
conn
Conn
)
ServerCodec
{
enc
:=
json
.
NewEncoder
(
conn
)
dec
:=
json
.
NewDecoder
(
conn
)
dec
.
UseNumber
()
return
NewFuncCodec
(
conn
,
enc
.
Encode
,
dec
.
Decode
)
}
func
(
c
*
jsonCodec
)
remoteAddr
()
string
{
return
c
.
remote
}
func
(
c
*
jsonCodec
)
readBatch
()
(
messages
[]
*
jsonrpcMessage
,
batch
bool
,
err
error
)
{
// Decode the next JSON object in the input stream.
// This verifies basic syntax, etc.
var
rawmsg
json
.
RawMessage
if
err
:=
c
.
decode
(
&
rawmsg
);
err
!=
nil
{
return
nil
,
false
,
err
}
messages
,
batch
=
parseMessage
(
rawmsg
)
for
i
,
msg
:=
range
messages
{
if
msg
==
nil
{
// Message is JSON 'null'. Replace with zero value so it
// will be treated like any other invalid message.
messages
[
i
]
=
new
(
jsonrpcMessage
)
}
}
return
messages
,
batch
,
nil
}
func
(
c
*
jsonCodec
)
writeJSON
(
ctx
context
.
Context
,
v
interface
{})
error
{
c
.
encMu
.
Lock
()
defer
c
.
encMu
.
Unlock
()
deadline
,
ok
:=
ctx
.
Deadline
()
if
!
ok
{
deadline
=
time
.
Now
()
.
Add
(
defaultWriteTimeout
)
}
c
.
conn
.
SetWriteDeadline
(
deadline
)
return
c
.
encode
(
v
)
}
func
(
c
*
jsonCodec
)
close
()
{
c
.
closer
.
Do
(
func
()
{
close
(
c
.
closeCh
)
c
.
conn
.
Close
()
})
}
// Closed returns a channel which will be closed when Close is called
func
(
c
*
jsonCodec
)
closed
()
<-
chan
interface
{}
{
return
c
.
closeCh
}
// parseMessage parses raw bytes as a (batch of) JSON-RPC message(s). There are no error
// checks in this function because the raw message has already been syntax-checked when it
// is called. Any non-JSON-RPC messages in the input return the zero value of
// jsonrpcMessage.
func
parseMessage
(
raw
json
.
RawMessage
)
([]
*
jsonrpcMessage
,
bool
)
{
if
!
isBatch
(
raw
)
{
msgs
:=
[]
*
jsonrpcMessage
{{}}
json
.
Unmarshal
(
raw
,
&
msgs
[
0
])
return
msgs
,
false
}
dec
:=
json
.
NewDecoder
(
bytes
.
NewReader
(
raw
))
dec
.
Token
()
// skip '['
var
msgs
[]
*
jsonrpcMessage
for
dec
.
More
()
{
msgs
=
append
(
msgs
,
new
(
jsonrpcMessage
))
dec
.
Decode
(
&
msgs
[
len
(
msgs
)
-
1
])
}
return
msgs
,
true
}
// isBatch returns true when the first non-whitespace characters is '['
func
isBatch
(
raw
json
.
RawMessage
)
bool
{
for
_
,
c
:=
range
raw
{
// skip insignificant whitespace (http://www.ietf.org/rfc/rfc4627.txt)
if
c
==
0x20
||
c
==
0x09
||
c
==
0x0a
||
c
==
0x0d
{
continue
}
return
c
==
'['
}
return
false
}
// parsePositionalArguments tries to parse the given args to an array of values with the
// given types. It returns the parsed values or an error when the args could not be
// parsed. Missing optional arguments are returned as reflect.Zero values.
func
parsePositionalArguments
(
rawArgs
json
.
RawMessage
,
types
[]
reflect
.
Type
)
([]
reflect
.
Value
,
error
)
{
dec
:=
json
.
NewDecoder
(
bytes
.
NewReader
(
rawArgs
))
var
args
[]
reflect
.
Value
tok
,
err
:=
dec
.
Token
()
switch
{
case
err
==
io
.
EOF
||
tok
==
nil
&&
err
==
nil
:
// "params" is optional and may be empty. Also allow "params":null even though it's
// not in the spec because our own client used to send it.
case
err
!=
nil
:
return
nil
,
err
case
tok
==
json
.
Delim
(
'['
)
:
// Read argument array.
if
args
,
err
=
parseArgumentArray
(
dec
,
types
);
err
!=
nil
{
return
nil
,
err
}
default
:
return
nil
,
errors
.
New
(
"non-array args"
)
}
// Set any missing args to nil.
for
i
:=
len
(
args
);
i
<
len
(
types
);
i
++
{
if
types
[
i
]
.
Kind
()
!=
reflect
.
Ptr
{
return
nil
,
fmt
.
Errorf
(
"missing value for required argument %d"
,
i
)
}
args
=
append
(
args
,
reflect
.
Zero
(
types
[
i
]))
}
return
args
,
nil
}
func
parseArgumentArray
(
dec
*
json
.
Decoder
,
types
[]
reflect
.
Type
)
([]
reflect
.
Value
,
error
)
{
args
:=
make
([]
reflect
.
Value
,
0
,
len
(
types
))
for
i
:=
0
;
dec
.
More
();
i
++
{
if
i
>=
len
(
types
)
{
return
args
,
fmt
.
Errorf
(
"too many arguments, want at most %d"
,
len
(
types
))
}
argval
:=
reflect
.
New
(
types
[
i
])
if
err
:=
dec
.
Decode
(
argval
.
Interface
());
err
!=
nil
{
return
args
,
fmt
.
Errorf
(
"invalid argument %d: %v"
,
i
,
err
)
}
if
argval
.
IsNil
()
&&
types
[
i
]
.
Kind
()
!=
reflect
.
Ptr
{
return
args
,
fmt
.
Errorf
(
"missing value for required argument %d"
,
i
)
}
args
=
append
(
args
,
argval
.
Elem
())
}
// Read end of args array.
_
,
err
:=
dec
.
Token
()
return
args
,
err
}
// parseSubscriptionName extracts the subscription name from an encoded argument array.
func
parseSubscriptionName
(
rawArgs
json
.
RawMessage
)
(
string
,
error
)
{
dec
:=
json
.
NewDecoder
(
bytes
.
NewReader
(
rawArgs
))
if
tok
,
_
:=
dec
.
Token
();
tok
!=
json
.
Delim
(
'['
)
{
return
""
,
errors
.
New
(
"non-array args"
)
}
v
,
_
:=
dec
.
Token
()
method
,
ok
:=
v
.
(
string
)
if
!
ok
{
return
""
,
errors
.
New
(
"expected subscription name as first argument"
)
}
return
method
,
nil
}
minigeth/rpc/types.go
0 → 100644
View file @
f948f078
// 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
(
"context"
"encoding/json"
"fmt"
"math"
"strconv"
"strings"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
)
// API describes the set of methods offered over the RPC interface
type
API
struct
{
Namespace
string
// namespace under which the rpc methods of Service are exposed
Version
string
// api version for DApp's
Service
interface
{}
// receiver instance which holds the methods
Public
bool
// indication if the methods must be considered safe for public use
}
// ServerCodec implements reading, parsing and writing RPC messages for the server side of
// a RPC session. Implementations must be go-routine safe since the codec can be called in
// multiple go-routines concurrently.
type
ServerCodec
interface
{
readBatch
()
(
msgs
[]
*
jsonrpcMessage
,
isBatch
bool
,
err
error
)
close
()
jsonWriter
}
// jsonWriter can write JSON messages to its underlying connection.
// Implementations must be safe for concurrent use.
type
jsonWriter
interface
{
writeJSON
(
context
.
Context
,
interface
{})
error
// Closed returns a channel which is closed when the connection is closed.
closed
()
<-
chan
interface
{}
// RemoteAddr returns the peer address of the connection.
remoteAddr
()
string
}
type
BlockNumber
int64
const
(
PendingBlockNumber
=
BlockNumber
(
-
2
)
LatestBlockNumber
=
BlockNumber
(
-
1
)
EarliestBlockNumber
=
BlockNumber
(
0
)
)
// UnmarshalJSON parses the given JSON fragment into a BlockNumber. It supports:
// - "latest", "earliest" or "pending" as string arguments
// - the block number
// Returned errors:
// - an invalid block number error when the given argument isn't a known strings
// - an out of range error when the given block number is either too little or too large
func
(
bn
*
BlockNumber
)
UnmarshalJSON
(
data
[]
byte
)
error
{
input
:=
strings
.
TrimSpace
(
string
(
data
))
if
len
(
input
)
>=
2
&&
input
[
0
]
==
'"'
&&
input
[
len
(
input
)
-
1
]
==
'"'
{
input
=
input
[
1
:
len
(
input
)
-
1
]
}
switch
input
{
case
"earliest"
:
*
bn
=
EarliestBlockNumber
return
nil
case
"latest"
:
*
bn
=
LatestBlockNumber
return
nil
case
"pending"
:
*
bn
=
PendingBlockNumber
return
nil
}
blckNum
,
err
:=
hexutil
.
DecodeUint64
(
input
)
if
err
!=
nil
{
return
err
}
if
blckNum
>
math
.
MaxInt64
{
return
fmt
.
Errorf
(
"block number larger than int64"
)
}
*
bn
=
BlockNumber
(
blckNum
)
return
nil
}
func
(
bn
BlockNumber
)
Int64
()
int64
{
return
(
int64
)(
bn
)
}
type
BlockNumberOrHash
struct
{
BlockNumber
*
BlockNumber
`json:"blockNumber,omitempty"`
BlockHash
*
common
.
Hash
`json:"blockHash,omitempty"`
RequireCanonical
bool
`json:"requireCanonical,omitempty"`
}
func
(
bnh
*
BlockNumberOrHash
)
UnmarshalJSON
(
data
[]
byte
)
error
{
type
erased
BlockNumberOrHash
e
:=
erased
{}
err
:=
json
.
Unmarshal
(
data
,
&
e
)
if
err
==
nil
{
if
e
.
BlockNumber
!=
nil
&&
e
.
BlockHash
!=
nil
{
return
fmt
.
Errorf
(
"cannot specify both BlockHash and BlockNumber, choose one or the other"
)
}
bnh
.
BlockNumber
=
e
.
BlockNumber
bnh
.
BlockHash
=
e
.
BlockHash
bnh
.
RequireCanonical
=
e
.
RequireCanonical
return
nil
}
var
input
string
err
=
json
.
Unmarshal
(
data
,
&
input
)
if
err
!=
nil
{
return
err
}
switch
input
{
case
"earliest"
:
bn
:=
EarliestBlockNumber
bnh
.
BlockNumber
=
&
bn
return
nil
case
"latest"
:
bn
:=
LatestBlockNumber
bnh
.
BlockNumber
=
&
bn
return
nil
case
"pending"
:
bn
:=
PendingBlockNumber
bnh
.
BlockNumber
=
&
bn
return
nil
default
:
if
len
(
input
)
==
66
{
hash
:=
common
.
Hash
{}
err
:=
hash
.
UnmarshalText
([]
byte
(
input
))
if
err
!=
nil
{
return
err
}
bnh
.
BlockHash
=
&
hash
return
nil
}
else
{
blckNum
,
err
:=
hexutil
.
DecodeUint64
(
input
)
if
err
!=
nil
{
return
err
}
if
blckNum
>
math
.
MaxInt64
{
return
fmt
.
Errorf
(
"blocknumber too high"
)
}
bn
:=
BlockNumber
(
blckNum
)
bnh
.
BlockNumber
=
&
bn
return
nil
}
}
}
func
(
bnh
*
BlockNumberOrHash
)
Number
()
(
BlockNumber
,
bool
)
{
if
bnh
.
BlockNumber
!=
nil
{
return
*
bnh
.
BlockNumber
,
true
}
return
BlockNumber
(
0
),
false
}
func
(
bnh
*
BlockNumberOrHash
)
Hash
()
(
common
.
Hash
,
bool
)
{
if
bnh
.
BlockHash
!=
nil
{
return
*
bnh
.
BlockHash
,
true
}
return
common
.
Hash
{},
false
}
func
BlockNumberOrHashWithNumber
(
blockNr
BlockNumber
)
BlockNumberOrHash
{
return
BlockNumberOrHash
{
BlockNumber
:
&
blockNr
,
BlockHash
:
nil
,
RequireCanonical
:
false
,
}
}
func
BlockNumberOrHashWithHash
(
hash
common
.
Hash
,
canonical
bool
)
BlockNumberOrHash
{
return
BlockNumberOrHash
{
BlockNumber
:
nil
,
BlockHash
:
&
hash
,
RequireCanonical
:
canonical
,
}
}
// DecimalOrHex unmarshals a non-negative decimal or hex parameter into a uint64.
type
DecimalOrHex
uint64
// UnmarshalJSON implements json.Unmarshaler.
func
(
dh
*
DecimalOrHex
)
UnmarshalJSON
(
data
[]
byte
)
error
{
input
:=
strings
.
TrimSpace
(
string
(
data
))
if
len
(
input
)
>=
2
&&
input
[
0
]
==
'"'
&&
input
[
len
(
input
)
-
1
]
==
'"'
{
input
=
input
[
1
:
len
(
input
)
-
1
]
}
value
,
err
:=
strconv
.
ParseUint
(
input
,
10
,
64
)
if
err
!=
nil
{
value
,
err
=
hexutil
.
DecodeUint64
(
input
)
}
if
err
!=
nil
{
return
err
}
*
dh
=
DecimalOrHex
(
value
)
return
nil
}
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment