import "github.com/ethereum/go-ethereum/p2p/simulations"
Package simulations simulates p2p networks. A mocker simulates starting and stopping real nodes in a network.
connect.go events.go http.go mocker.go network.go simulation.go test.go
DefaultClient is the default simulation API client which expects the API to be running at http://localhost:8888
var DialBanTimeout = 200 * time.Millisecond
ConnLabel generates a deterministic string which represents a connection between two nodes, used to compare if two connections are between the same nodes
Get a list of mockers (keys of the map) Useful for frontend to build available mocker selection
Lookup a mocker by its name, returns the mockerFn
Client is a client for the simulation HTTP API which supports creating and managing simulation networks
NewClient returns a new simulation API client
ConnectNode connects a node to a peer node
CreateNode creates a node in the network using the given configuration
CreateSnapshot creates a network snapshot
Delete performs a HTTP DELETE request
DisconnectNode disconnects a node from a peer node
Get performs a HTTP GET request decoding the resulting JSON response into "out"
GetNetwork returns details of the network
GetNode returns details of a node
GetNodes returns all nodes which exist in the network
LoadSnapshot loads a snapshot into the network
Post performs a HTTP POST request sending "in" as the JSON body and decoding the resulting JSON response into "out"
RPCClient returns an RPC client connected to a node
Send performs a HTTP request, sending "in" as the JSON request body and decoding the JSON response into "out"
StartNetwork starts all existing nodes in the simulation network
StartNode starts a node
StopNetwork stops all existing nodes in a simulation network
StopNode stops a node
func (c *Client) SubscribeNetwork(events chan *Event, opts SubscribeOpts) (event.Subscription, error)
SubscribeNetwork subscribes to network events which are sent from the server as a server-sent-events stream, optionally receiving events for existing nodes and connections and filtering message events
type Conn struct { // One is the node which initiated the connection One enode.ID `json:"one"` // Other is the node which the connection was made to Other enode.ID `json:"other"` // Up tracks whether or not the connection is active Up bool `json:"up"` // contains filtered or unexported fields }
Conn represents a connection between two nodes in the network
String returns a log-friendly string
type Event struct { // Type is the type of the event Type EventType `json:"type"` // Time is the time the event happened Time time.Time `json:"time"` // Control indicates whether the event is the result of a controlled // action in the network Control bool `json:"control"` // Node is set if the type is EventTypeNode Node *Node `json:"node,omitempty"` // Conn is set if the type is EventTypeConn Conn *Conn `json:"conn,omitempty"` // Msg is set if the type is EventTypeMsg Msg *Msg `json:"msg,omitempty"` //Optionally provide data (currently for simulation frontends only) Data interface{} `json:"data"` }
Event is an event emitted by a simulation network
ControlEvent creates a new control event
NewEvent creates a new event for the given object which should be either a Node, Conn or Msg.
The object is copied so that the event represents the state of the object when NewEvent is called.
String returns the string representation of the event
EventType is the type of event emitted by a simulation network
const ( // EventTypeNode is the type of event emitted when a node is either // created, started or stopped EventTypeNode EventType = "node" // EventTypeConn is the type of event emitted when a connection is // is either established or dropped between two nodes EventTypeConn EventType = "conn" // EventTypeMsg is the type of event emitted when a p2p message it // sent between two nodes EventTypeMsg EventType = "msg" )
type Expectation struct { // Nodes is a list of nodes to check Nodes []enode.ID // Check checks whether a given node meets the expectation Check func(context.Context, enode.ID) (bool, error) }
type Msg struct { One enode.ID `json:"one"` Other enode.ID `json:"other"` Protocol string `json:"protocol"` Code uint64 `json:"code"` Received bool `json:"received"` }
Msg represents a p2p message sent between two nodes in the network
String returns a log-friendly string
type MsgFilter struct { // Proto is matched against a message's protocol Proto string // Code is matched against a message's code, with -1 matching all codes Code int64 }
MsgFilter is used to filter message events based on protocol and message code
MsgFilters is a collection of filters which are used to filter message events
func NewMsgFilters(filterParam string) (MsgFilters, error)
NewMsgFilters constructs a collection of message filters from a URL query parameter.
The parameter is expected to be a dash-separated list of individual filters, each having the format '<proto>:<codes>', where <proto> is the name of a protocol and <codes> is a comma-separated list of message codes.
A message code of '*' or '-1' is considered a wildcard and matches any code.
func (m MsgFilters) Match(msg *Msg) bool
Match checks if the given message matches any of the filters
type Network struct { NetworkConfig Nodes []*Node `json:"nodes"` Conns []*Conn `json:"conns"` // contains filtered or unexported fields }
Network models a p2p simulation network which consists of a collection of simulated nodes and the connections which exist between them.
The Network has a single NodeAdapter which is responsible for actually starting nodes and connecting them together.
The Network emits events when nodes are started and stopped, when they are connected and disconnected, and also when messages are sent between nodes.
func NewNetwork(nodeAdapter adapters.NodeAdapter, conf *NetworkConfig) *Network
NewNetwork returns a Network which uses the given NodeAdapter and NetworkConfig
func (net *Network) Config() *NetworkConfig
Config returns the network configuration
Connect connects two nodes together by calling the "admin_addPeer" RPC method on the "one" node so that it connects to the "other" node
ConnectNodesChain connects all nodes in a chain topology. If ids argument is nil, all nodes that are up will be connected.
ConnectNodesFull connects all nodes one to another. It provides a complete connectivity in the network which should be rarely needed.
ConnectNodesRing connects all nodes in a ring topology. If ids argument is nil, all nodes that are up will be connected.
ConnectNodesStar connects all nodes into a star topology If ids argument is nil, all nodes that are up will be connected.
ConnectToLastNode connects the node with provided NodeID to the last node that is up, and avoiding connection to self. It is useful when constructing a chain network topology when Network adds and removes nodes dynamically.
ConnectToRandomNode connects the node with provided NodeID to a random node that is up.
DidConnect tracks the fact that the "one" node connected to the "other" node
DidDisconnect tracks the fact that the "one" node disconnected from the "other" node
DidReceive tracks the fact that "receiver" received a message from "sender"
DidSend tracks the fact that "sender" sent a message to "receiver"
Disconnect disconnects two nodes by calling the "admin_removePeer" RPC method on the "one" node so that it disconnects from the "other" node
Events returns the output event feed of the Network.
GetConn returns the connection which exists between "one" and "other" regardless of which node initiated the connection
GetNode gets the node with the given ID, returning nil if the node does not exist
GetNodeByName gets the node with the given name, returning nil if the node does not exist
GetNodeIDs returns the IDs of all existing nodes Nodes can optionally be excluded by specifying their enode.ID.
GetNodeIDsByProperty returns existing node's enode IDs that have the given property string registered in the NodeConfig
GetNodes returns the existing nodes. Nodes can optionally be excluded by specifying their enode.ID.
GetNodesByID returns existing nodes with the given enode.IDs. If a node doesn't exist with a given enode.ID, it is ignored.
GetNodesByProperty returns existing nodes that have the given property string registered in their NodeConfig
GetOrCreateConn is like GetConn but creates the connection if it doesn't already exist
GetRandomDownNode returns a random node on the network, which is stopped.
GetRandomNode returns a random node on the network, regardless of whether it is running or not
GetRandomUpNode returns a random node on the network, which is running.
InitConn(one, other) retrieves the connection model for the connection between peers one and other, or creates a new one if it does not exist the order of nodes does not matter, i.e., Conn(i,j) == Conn(j, i) it checks if the connection is already up, and if the nodes are running NOTE: it also checks whether there has been recent attempt to connect the peers this is cheating as the simulation is used as an oracle and know about remote peers attempt to connect to a node which will then not initiate the connection
Load loads a network snapshot
NewNodeWithConfig adds a new node to the network with the given config, returning an error if a node with the same ID or name already exists
Reset resets all network properties: empties the nodes and the connection list
Shutdown stops all nodes in the network and closes the quit channel
Snapshot creates a network snapshot
func (net *Network) SnapshotWithServices(addServices []string, removeServices []string) (*Snapshot, error)
Start starts the node with the given ID
StartAll starts all nodes in the network
Stop stops the node with the given ID
StopAll stops all nodes in the network
Subscribe reads control events from a channel and executes them
type NetworkConfig struct { ID string `json:"id"` DefaultService string `json:"default_service,omitempty"` }
NetworkConfig defines configuration options for starting a Network
type Node struct { adapters.Node `json:"-"` // Config if the config used to created the node Config *adapters.NodeConfig `json:"config"` // contains filtered or unexported fields }
Node is a wrapper around adapters.Node which is used to track the status of a node in the network
ID returns the ID of the node
MarshalJSON implements the json.Marshaler interface so that the encoded JSON includes the NodeInfo
NodeInfo returns information about the node
SetUp sets the up (online) status of the nodes with the given value
String returns a log-friendly string
UnmarshalJSON implements json.Unmarshaler interface so that we don't lose Node.up status. IMPORTANT: The implementation is incomplete; we lose p2p.NodeInfo.
Up returns whether the node is currently up (online)
type NodeSnapshot struct { Node Node `json:"node,omitempty"` // Snapshots is arbitrary data gathered from calling node.Snapshots() Snapshots map[string][]byte `json:"snapshots,omitempty"` }
NodeSnapshot represents the state of a node in the network
type NoopService struct {
// contains filtered or unexported fields
}
NoopService is the service that does not do anything but implements node.Service interface.
func NewNoopService(ackC map[enode.ID]chan struct{}) *NoopService
func (t *NoopService) APIs() []rpc.API
func (t *NoopService) Protocols() []p2p.Protocol
func (t *NoopService) Start() error
func (t *NoopService) Stop() error
type Server struct {
// contains filtered or unexported fields
}
Server is an HTTP server providing an API to manage a simulation network
NewServer returns a new simulation API server
ConnectNode connects a node to a peer node
CreateNode creates a node in the network using the given configuration
CreateSnapshot creates a network snapshot
func (s *Server) DELETE(path string, handle http.HandlerFunc)
DELETE registers a handler for DELETE requests to a particular path
DisconnectNode disconnects a node from a peer node
func (s *Server) GET(path string, handle http.HandlerFunc)
GET registers a handler for GET requests to a particular path
GetMockerList returns a list of available mockers
GetNetwork returns details of the network
GetNode returns details of a node
GetNodes returns all nodes which exist in the network
func (s *Server) JSON(w http.ResponseWriter, status int, data interface{})
JSON sends "data" as a JSON HTTP response
LoadSnapshot loads a snapshot into the network
NodeRPC forwards RPC requests to a node in the network via a WebSocket connection
func (s *Server) OPTIONS(path string, handle http.HandlerFunc)
OPTIONS registers a handler for OPTIONS requests to a particular path
Options responds to the OPTIONS HTTP method by returning a 200 OK response with the "Access-Control-Allow-Headers" header set to "Content-Type"
func (s *Server) POST(path string, handle http.HandlerFunc)
POST registers a handler for POST requests to a particular path
ResetNetwork resets all properties of a network to its initial (empty) state
ServeHTTP implements the http.Handler interface by delegating to the underlying httprouter.Router
StartMocker starts the mocker node simulation
StartNetwork starts all nodes in the network
StartNode starts a node
StopMocker stops the mocker node simulation
StopNetwork stops all nodes in the network
StopNode stops a node
StreamNetworkEvents streams network events as a server-sent-events stream
type Simulation struct {
// contains filtered or unexported fields
}
Simulation provides a framework for running actions in a simulated network and then waiting for expectations to be met
func NewSimulation(network *Network) *Simulation
NewSimulation returns a new simulation which runs in the given network
func (s *Simulation) Run(ctx context.Context, step *Step) (result *StepResult)
Run performs a step of the simulation by performing the step's action and then waiting for the step's expectation to be met
type Snapshot struct { Nodes []NodeSnapshot `json:"nodes,omitempty"` Conns []Conn `json:"conns,omitempty"` }
Snapshot represents the state of a network at a single point in time and can be used to restore the state of a network
type Step struct { // Action is the action to perform for this step Action func(context.Context) error // Trigger is a channel which receives node ids and triggers an // expectation check for that node Trigger chan enode.ID // Expect is the expectation to wait for when performing this step Expect *Expectation }
type StepResult struct { // Error is the error encountered whilst running the step Error error // StartedAt is the time the step started StartedAt time.Time // FinishedAt is the time the step finished FinishedAt time.Time // Passes are the timestamps of the successful node expectations Passes map[enode.ID]time.Time // NetworkEvents are the network events which occurred during the step NetworkEvents []*Event }
type SubscribeOpts struct { // Current instructs the server to send events for existing nodes and // connections first Current bool // Filter instructs the server to only send a subset of message events Filter string }
SubscribeOpts is a collection of options to use when subscribing to network events
Path | Synopsis |
---|---|
adapters | |
examples | |
pipes |
Package simulations imports 24 packages (graph) and is imported by 297 packages. Updated 2021-01-14. Refresh now. Tools for package owners.