go-ethereum: github.com/axiomzen/go-ethereum/p2p/simulations Index | Files | Directories

package simulations

import "github.com/axiomzen/go-ethereum/p2p/simulations"

Package simulations simulates p2p networks. A mocker simulates starting and stopping real nodes in a network.

Index

Package Files

connect.go events.go http.go mocker.go network.go simulation.go test.go

Variables

var DefaultClient = NewClient("http://localhost:8888")

DefaultClient is the default simulation API client which expects the API to be running at http://localhost:8888

var DialBanTimeout = 200 * time.Millisecond
var (
    ErrNodeNotFound = errors.New("node not found")
)

func ConnLabel Uses

func ConnLabel(source, target enode.ID) string

ConnLabel generates a deterministic string which represents a connection between two nodes, used to compare if two connections are between the same nodes

func GetMockerList Uses

func GetMockerList() []string

Get a list of mockers (keys of the map) Useful for frontend to build available mocker selection

func LookupMocker Uses

func LookupMocker(mockerType string) func(net *Network, quit chan struct{}, nodeCount int)

Lookup a mocker by its name, returns the mockerFn

func VerifyChain Uses

func VerifyChain(t *testing.T, net *Network, ids []enode.ID)

func VerifyFull Uses

func VerifyFull(t *testing.T, net *Network, ids []enode.ID)

func VerifyRing Uses

func VerifyRing(t *testing.T, net *Network, ids []enode.ID)

func VerifyStar Uses

func VerifyStar(t *testing.T, net *Network, ids []enode.ID, centerIndex int)

type Client Uses

type Client struct {
    URL string
    // contains filtered or unexported fields
}

Client is a client for the simulation HTTP API which supports creating and managing simulation networks

func NewClient Uses

func NewClient(url string) *Client

NewClient returns a new simulation API client

func (*Client) ConnectNode Uses

func (c *Client) ConnectNode(nodeID, peerID string) error

ConnectNode connects a node to a peer node

func (*Client) CreateNode Uses

func (c *Client) CreateNode(config *adapters.NodeConfig) (*p2p.NodeInfo, error)

CreateNode creates a node in the network using the given configuration

func (*Client) CreateSnapshot Uses

func (c *Client) CreateSnapshot() (*Snapshot, error)

CreateSnapshot creates a network snapshot

func (*Client) Delete Uses

func (c *Client) Delete(path string) error

Delete performs a HTTP DELETE request

func (*Client) DisconnectNode Uses

func (c *Client) DisconnectNode(nodeID, peerID string) error

DisconnectNode disconnects a node from a peer node

func (*Client) Get Uses

func (c *Client) Get(path string, out interface{}) error

Get performs a HTTP GET request decoding the resulting JSON response into "out"

func (*Client) GetNetwork Uses

func (c *Client) GetNetwork() (*Network, error)

GetNetwork returns details of the network

func (*Client) GetNode Uses

func (c *Client) GetNode(nodeID string) (*p2p.NodeInfo, error)

GetNode returns details of a node

func (*Client) GetNodes Uses

func (c *Client) GetNodes() ([]*p2p.NodeInfo, error)

GetNodes returns all nodes which exist in the network

func (*Client) LoadSnapshot Uses

func (c *Client) LoadSnapshot(snap *Snapshot) error

LoadSnapshot loads a snapshot into the network

func (*Client) Post Uses

func (c *Client) Post(path string, in, out interface{}) error

Post performs a HTTP POST request sending "in" as the JSON body and decoding the resulting JSON response into "out"

func (*Client) RPCClient Uses

func (c *Client) RPCClient(ctx context.Context, nodeID string) (*rpc.Client, error)

RPCClient returns an RPC client connected to a node

func (*Client) Send Uses

func (c *Client) Send(method, path string, in, out interface{}) error

Send performs a HTTP request, sending "in" as the JSON request body and decoding the JSON response into "out"

func (*Client) StartNetwork Uses

func (c *Client) StartNetwork() error

StartNetwork starts all existing nodes in the simulation network

func (*Client) StartNode Uses

func (c *Client) StartNode(nodeID string) error

StartNode starts a node

func (*Client) StopNetwork Uses

func (c *Client) StopNetwork() error

StopNetwork stops all existing nodes in a simulation network

func (*Client) StopNode Uses

func (c *Client) StopNode(nodeID string) error

StopNode stops a node

func (*Client) SubscribeNetwork Uses

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 Uses

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

func (*Conn) String Uses

func (c *Conn) String() string

String returns a log-friendly string

type Event Uses

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

func ControlEvent Uses

func ControlEvent(v interface{}) *Event

ControlEvent creates a new control event

func NewEvent Uses

func NewEvent(v interface{}) *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.

func (*Event) String Uses

func (e *Event) String() string

String returns the string representation of the event

type EventType Uses

type EventType string

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 Uses

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 Uses

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

func (*Msg) String Uses

func (m *Msg) String() string

String returns a log-friendly string

type MsgFilter Uses

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

type MsgFilters Uses

type MsgFilters map[MsgFilter]struct{}

MsgFilters is a collection of filters which are used to filter message events

func NewMsgFilters Uses

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 (MsgFilters) Match Uses

func (m MsgFilters) Match(msg *Msg) bool

Match checks if the given message matches any of the filters

type Network Uses

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 Uses

func NewNetwork(nodeAdapter adapters.NodeAdapter, conf *NetworkConfig) *Network

NewNetwork returns a Network which uses the given NodeAdapter and NetworkConfig

func (*Network) Config Uses

func (net *Network) Config() *NetworkConfig

Config returns the network configuration

func (*Network) Connect Uses

func (net *Network) Connect(oneID, otherID enode.ID) error

Connect connects two nodes together by calling the "admin_addPeer" RPC method on the "one" node so that it connects to the "other" node

func (*Network) ConnectNodesChain Uses

func (net *Network) ConnectNodesChain(ids []enode.ID) (err error)

ConnectNodesChain connects all nodes in a chain topology. If ids argument is nil, all nodes that are up will be connected.

func (*Network) ConnectNodesFull Uses

func (net *Network) ConnectNodesFull(ids []enode.ID) (err error)

ConnectNodesFull connects all nodes one to another. It provides a complete connectivity in the network which should be rarely needed.

func (*Network) ConnectNodesRing Uses

func (net *Network) ConnectNodesRing(ids []enode.ID) (err error)

ConnectNodesRing connects all nodes in a ring topology. If ids argument is nil, all nodes that are up will be connected.

func (*Network) ConnectNodesStar Uses

func (net *Network) ConnectNodesStar(ids []enode.ID, center enode.ID) (err error)

ConnectNodesStar connects all nodes into a star topology If ids argument is nil, all nodes that are up will be connected.

func (*Network) ConnectToLastNode Uses

func (net *Network) ConnectToLastNode(id enode.ID) (err error)

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.

func (*Network) ConnectToRandomNode Uses

func (net *Network) ConnectToRandomNode(id enode.ID) (err error)

ConnectToRandomNode connects the node with provided NodeID to a random node that is up.

func (*Network) DidConnect Uses

func (net *Network) DidConnect(one, other enode.ID) error

DidConnect tracks the fact that the "one" node connected to the "other" node

func (*Network) DidDisconnect Uses

func (net *Network) DidDisconnect(one, other enode.ID) error

DidDisconnect tracks the fact that the "one" node disconnected from the "other" node

func (*Network) DidReceive Uses

func (net *Network) DidReceive(sender, receiver enode.ID, proto string, code uint64) error

DidReceive tracks the fact that "receiver" received a message from "sender"

func (*Network) DidSend Uses

func (net *Network) DidSend(sender, receiver enode.ID, proto string, code uint64) error

DidSend tracks the fact that "sender" sent a message to "receiver"

func (*Network) Disconnect Uses

func (net *Network) Disconnect(oneID, otherID enode.ID) error

Disconnect disconnects two nodes by calling the "admin_removePeer" RPC method on the "one" node so that it disconnects from the "other" node

func (*Network) Events Uses

func (net *Network) Events() *event.Feed

Events returns the output event feed of the Network.

func (*Network) GetConn Uses

func (net *Network) GetConn(oneID, otherID enode.ID) *Conn

GetConn returns the connection which exists between "one" and "other" regardless of which node initiated the connection

func (*Network) GetNode Uses

func (net *Network) GetNode(id enode.ID) *Node

GetNode gets the node with the given ID, returning nil if the node does not exist

func (*Network) GetNodeByName Uses

func (net *Network) GetNodeByName(name string) *Node

GetNode gets the node with the given name, returning nil if the node does not exist

func (*Network) GetNodes Uses

func (net *Network) GetNodes() (nodes []*Node)

GetNodes returns the existing nodes

func (*Network) GetOrCreateConn Uses

func (net *Network) GetOrCreateConn(oneID, otherID enode.ID) (*Conn, error)

GetOrCreateConn is like GetConn but creates the connection if it doesn't already exist

func (*Network) GetRandomDownNode Uses

func (net *Network) GetRandomDownNode(excludeIDs ...enode.ID) *Node

GetRandomDownNode returns a random node on the network, which is stopped.

func (*Network) GetRandomUpNode Uses

func (net *Network) GetRandomUpNode(excludeIDs ...enode.ID) *Node

GetRandomUpNode returns a random node on the network, which is running.

func (*Network) InitConn Uses

func (net *Network) InitConn(oneID, otherID enode.ID) (*Conn, error)

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

func (*Network) Load Uses

func (net *Network) Load(snap *Snapshot) error

Load loads a network snapshot

func (*Network) NewNodeWithConfig Uses

func (net *Network) NewNodeWithConfig(conf *adapters.NodeConfig) (*Node, error)

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

func (*Network) Reset Uses

func (net *Network) Reset()

Reset resets all network properties: empties the nodes and the connection list

func (*Network) Shutdown Uses

func (net *Network) Shutdown()

Shutdown stops all nodes in the network and closes the quit channel

func (*Network) Snapshot Uses

func (net *Network) Snapshot() (*Snapshot, error)

Snapshot creates a network snapshot

func (*Network) SnapshotWithServices Uses

func (net *Network) SnapshotWithServices(addServices []string, removeServices []string) (*Snapshot, error)

func (*Network) Start Uses

func (net *Network) Start(id enode.ID) error

Start starts the node with the given ID

func (*Network) StartAll Uses

func (net *Network) StartAll() error

StartAll starts all nodes in the network

func (*Network) Stop Uses

func (net *Network) Stop(id enode.ID) error

Stop stops the node with the given ID

func (*Network) StopAll Uses

func (net *Network) StopAll() error

StopAll stops all nodes in the network

func (*Network) Subscribe Uses

func (net *Network) Subscribe(events chan *Event)

Subscribe reads control events from a channel and executes them

type NetworkConfig Uses

type NetworkConfig struct {
    ID             string `json:"id"`
    DefaultService string `json:"default_service,omitempty"`
}

NetworkConfig defines configuration options for starting a Network

type Node Uses

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

func (*Node) ID Uses

func (n *Node) ID() enode.ID

ID returns the ID of the node

func (*Node) MarshalJSON Uses

func (n *Node) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface so that the encoded JSON includes the NodeInfo

func (*Node) NodeInfo Uses

func (n *Node) NodeInfo() *p2p.NodeInfo

NodeInfo returns information about the node

func (*Node) SetUp Uses

func (n *Node) SetUp(up bool)

func (*Node) String Uses

func (n *Node) String() string

String returns a log-friendly string

func (*Node) UnmarshalJSON Uses

func (n *Node) UnmarshalJSON(raw []byte) error

UnmarshalJSON implements json.Unmarshaler interface so that we don't lose Node.up status. IMPORTANT: The implementation is incomplete; we lose p2p.NodeInfo.

func (*Node) Up Uses

func (n *Node) Up() bool

type NodeSnapshot Uses

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 Uses

type NoopService struct {
    // contains filtered or unexported fields
}

NoopService is the service that does not do anything but implements node.Service interface.

func NewNoopService Uses

func NewNoopService(ackC map[enode.ID]chan struct{}) *NoopService

func (*NoopService) APIs Uses

func (t *NoopService) APIs() []rpc.API

func (*NoopService) Protocols Uses

func (t *NoopService) Protocols() []p2p.Protocol

func (*NoopService) Start Uses

func (t *NoopService) Start(server *p2p.Server) error

func (*NoopService) Stop Uses

func (t *NoopService) Stop() error

type Server Uses

type Server struct {
    // contains filtered or unexported fields
}

Server is an HTTP server providing an API to manage a simulation network

func NewServer Uses

func NewServer(network *Network) *Server

NewServer returns a new simulation API server

func (*Server) ConnectNode Uses

func (s *Server) ConnectNode(w http.ResponseWriter, req *http.Request)

ConnectNode connects a node to a peer node

func (*Server) CreateNode Uses

func (s *Server) CreateNode(w http.ResponseWriter, req *http.Request)

CreateNode creates a node in the network using the given configuration

func (*Server) CreateSnapshot Uses

func (s *Server) CreateSnapshot(w http.ResponseWriter, req *http.Request)

CreateSnapshot creates a network snapshot

func (*Server) DELETE Uses

func (s *Server) DELETE(path string, handle http.HandlerFunc)

DELETE registers a handler for DELETE requests to a particular path

func (*Server) DisconnectNode Uses

func (s *Server) DisconnectNode(w http.ResponseWriter, req *http.Request)

DisconnectNode disconnects a node from a peer node

func (*Server) GET Uses

func (s *Server) GET(path string, handle http.HandlerFunc)

GET registers a handler for GET requests to a particular path

func (*Server) GetMockers Uses

func (s *Server) GetMockers(w http.ResponseWriter, req *http.Request)

GetMockerList returns a list of available mockers

func (*Server) GetNetwork Uses

func (s *Server) GetNetwork(w http.ResponseWriter, req *http.Request)

GetNetwork returns details of the network

func (*Server) GetNode Uses

func (s *Server) GetNode(w http.ResponseWriter, req *http.Request)

GetNode returns details of a node

func (*Server) GetNodes Uses

func (s *Server) GetNodes(w http.ResponseWriter, req *http.Request)

GetNodes returns all nodes which exist in the network

func (*Server) JSON Uses

func (s *Server) JSON(w http.ResponseWriter, status int, data interface{})

JSON sends "data" as a JSON HTTP response

func (*Server) LoadSnapshot Uses

func (s *Server) LoadSnapshot(w http.ResponseWriter, req *http.Request)

LoadSnapshot loads a snapshot into the network

func (*Server) NodeRPC Uses

func (s *Server) NodeRPC(w http.ResponseWriter, req *http.Request)

NodeRPC forwards RPC requests to a node in the network via a WebSocket connection

func (*Server) OPTIONS Uses

func (s *Server) OPTIONS(path string, handle http.HandlerFunc)

OPTIONS registers a handler for OPTIONS requests to a particular path

func (*Server) Options Uses

func (s *Server) Options(w http.ResponseWriter, req *http.Request)

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 (*Server) POST Uses

func (s *Server) POST(path string, handle http.HandlerFunc)

POST registers a handler for POST requests to a particular path

func (*Server) ResetNetwork Uses

func (s *Server) ResetNetwork(w http.ResponseWriter, req *http.Request)

ResetNetwork resets all properties of a network to its initial (empty) state

func (*Server) ServeHTTP Uses

func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP implements the http.Handler interface by delegating to the underlying httprouter.Router

func (*Server) StartMocker Uses

func (s *Server) StartMocker(w http.ResponseWriter, req *http.Request)

StartMocker starts the mocker node simulation

func (*Server) StartNetwork Uses

func (s *Server) StartNetwork(w http.ResponseWriter, req *http.Request)

StartNetwork starts all nodes in the network

func (*Server) StartNode Uses

func (s *Server) StartNode(w http.ResponseWriter, req *http.Request)

StartNode starts a node

func (*Server) StopMocker Uses

func (s *Server) StopMocker(w http.ResponseWriter, req *http.Request)

StopMocker stops the mocker node simulation

func (*Server) StopNetwork Uses

func (s *Server) StopNetwork(w http.ResponseWriter, req *http.Request)

StopNetwork stops all nodes in the network

func (*Server) StopNode Uses

func (s *Server) StopNode(w http.ResponseWriter, req *http.Request)

StopNode stops a node

func (*Server) StreamNetworkEvents Uses

func (s *Server) StreamNetworkEvents(w http.ResponseWriter, req *http.Request)

StreamNetworkEvents streams network events as a server-sent-events stream

type Simulation Uses

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 Uses

func NewSimulation(network *Network) *Simulation

NewSimulation returns a new simulation which runs in the given network

func (*Simulation) Run Uses

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 Uses

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 Uses

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 Uses

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 Uses

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

Directories

PathSynopsis
adapters
pipes

Package simulations imports 24 packages (graph). Updated 2019-07-06. Refresh now. Tools for package owners.