network

package
v0.0.0-...-15eb78e Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 30, 2022 License: AGPL-3.0 Imports: 37 Imported by: 0

Documentation

Index

Constants

View Source
const AddressHeader = "X-Algorand-Location"

AddressHeader HTTP header by which an inbound connection reports its public address AddressHeader 인바운드 연결이 공개 주소를 보고하는 HTTP 헤더

View Source
const (
	ErrorKey = "Error" // used for passing an error message
)

Constant strings used as keys for topics 토픽의 키로 사용되는 상수 문자열

View Source
const GenesisHeader = "X-Algorand-Genesis"

GenesisHeader HTTP header for genesis id to make sure we're on the same chain GenesisHeader 동일한 체인에 있는지 확인하기 위한 Genesis id용 HTTP 헤더

View Source
const GossipNetworkPath = "/v1/{genesisID}/gossip"

WebsocketNetwork implements WebsocketNetwork는 GossipNode를 구현합니다.

GossipNetworkPath는 웹소켓 가십노드와 연결하기 위한 url경로이다.
View Source
const InstanceNameHeader = "X-Algorand-InstanceName"

InstanceNameHeader HTTP header by which an inbound connection reports an ID to distinguish multiple local nodes. InstanceNameHeader 인바운드 연결이 여러 로컬 노드를 구별하기 위해 ID를 보고하는 HTTP 헤더입니다.

View Source
const NodeRandomHeader = "X-Algorand-NodeRandom"

NodeRandomHeader HTTP header that a node uses to make sure it's not talking to itself NodeRandomHeader 노드가 자신과 통신하지 않는지 확인하기 위해 사용하는 HTTP 헤더

View Source
const PhoneBookEntryArchiverRole = 2

PhoneBookEntryArchiverRole used for all the archivers that are provided via the archive SRV record. 아카이브 SRV 레코드를 통해 제공되는 모든 아카이버에 사용되는 PhoneBookEntryArchiverRole.

View Source
const PhoneBookEntryRelayRole = 1

PhoneBookEntryRelayRole used for all the relays that are provided either via the algobootstrap SRV record or via a configuration file. algobootstrap SRV 레코드 또는 구성 파일을 통해 제공되는 모든 릴레이에 사용되는 PhoneBookEntryRelayRole.

View Source
const PriorityChallengeHeader = "X-Algorand-PriorityChallenge"

PriorityChallengeHeader HTTP header informs a client about the challenge it should sign to increase network priority. PriorityChallengeHeader HTTP 헤더는 클라이언트에게 네트워크 우선 순위를 높이기 위해 서명해야 하는 챌린지를 알려줍니다.

View Source
const ProtocolAcceptVersionHeader = "X-Algorand-Accept-Version"

ProtocolAcceptVersionHeader HTTP header for accept protocol version. Client use this to advertise supported protocol versions. ProtocolAcceptVersionHeader 프로토콜 버전을 수락하기 위한 HTTP 헤더입니다. 클라이언트는 이것을 사용하여 지원되는 프로토콜 버전을 광고합니다.

View Source
const ProtocolVersion = "2.1"

ProtocolVersion is the current version attached to the ProtocolVersionHeader header

Version history:
*  1   Catchup service over websocket connections with unicast messages between peers
*  2.1 Introduced topic key/data pairs and enabled services over the gossip connections

ProtocolVersion은 ProtocolVersionHeader 헤더에 첨부된 현재 버전입니다.

버전 기록:
* 1 피어 간의 유니캐스트 메시지로 웹 소켓 연결을 통한 캐치업 서비스
* 2.1 가십 연결을 통해 주제 키/데이터 쌍 및 활성화된 서비스 도입
View Source
const ProtocolVersionHeader = "X-Algorand-Version"

ProtocolVersionHeader HTTP header for protocol version. ProtocolVersionHeader 프로토콜 버전에 대한 HTTP 헤더입니다.

View Source
const TelemetryIDHeader = "X-Algorand-TelId"

TelemetryIDHeader HTTP header for telemetry-id for logging TelemetryIDHeader 로깅을 위한 원격 측정 ID용 HTTP 헤더

View Source
const TooManyRequestsRetryAfterHeader = "Retry-After"

TooManyRequestsRetryAfterHeader HTTP header let the client know when to make the next connection attempt TooManyRequestsRetryAfterHeader HTTP 헤더는 클라이언트가 다음 연결을 시도할 시기를 알려줍니다.

View Source
const UserAgentHeader = "User-Agent"

UserAgentHeader is the HTTP header identify the user agent. UserAgentHeader는 사용자 에이전트를 식별하는 HTTP 헤더입니다.

Variables

View Source
var ErrConnectionQueueingTimeout = errors.New("rateLimitingTransport: queueing timeout")

ErrConnectionQueueingTimeout indicates that we've exceeded the time allocated for queueing the current request before the request attempt could be made. ErrConnectionQueueingTimeout은 요청 시도가 이루어지기 전에 현재 요청을 대기열에 넣는 데 할당된 시간을 초과했음을 나타냅니다.

View Source
var ErrIncomingMsgTooLarge = errors.New("read limit exceeded")

ErrIncomingMsgTooLarge is returned when an incoming message is too large 수신 메시지가 너무 크면 ErrIncomingMsgTooLarge가 반환됩니다.

View Source
var HostColonPortPattern = regexp.MustCompile("^[-a-zA-Z0-9.]+:\\d+$")

HostColonPortPattern matches "^[-a-zA-Z0-9.]+:\\d+$" e.g. "foo.com.:1234"

View Source
var SupportedProtocolVersions = []string{"2.1"}

SupportedProtocolVersions contains the list of supported protocol versions by this node ( in order of preference ). SupportedProtocolVersions에는 이 노드가 지원하는 프로토콜 버전 목록이 포함되어 있습니다(기본 설정 순서).

Functions

func MarshallMessageOfInterest

func MarshallMessageOfInterest(messageTags []protocol.Tag) []byte

MarshallMessageOfInterest generate a message of interest message body for a given set of message tags. MarshallMessageOfInterest는 주어진 메시지 태그 세트에 대한 관심 메시지 본문을 생성합니다.

func MarshallMessageOfInterestMap

func MarshallMessageOfInterestMap(tagmap map[protocol.Tag]bool) []byte

MarshallMessageOfInterestMap generates a message of interest message body for the message tags that map to "true" in the map argument. MarshallMessageOfInterestMap은 map 인수에서 "true"로 매핑되는 메시지 태그에 대한 관심 메시지 메시지 본문을 생성합니다.

func ParseHostOrURL

func ParseHostOrURL(addr string) (*url.URL, error)

ParseHostOrURL handles "host:port" or a full URL. ParseHostOrURL은 "host:port" 또는 전체 URL을 처리합니다. Standard library net/url.Parse chokes on "host:port". 표준 라이브러리 net/url.Parse는 "host:port"에서 chokes 합니다.

func SetUserAgentHeader

func SetUserAgentHeader(header http.Header)

SetUserAgentHeader adds the User-Agent header to the provided heades map. SetUserAgentHeader는 제공된 헤더 맵에 User-Agent 헤더를 추가합니다.

Types

type Dialer

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

Dialer establish tcp-level connection with the destination 다이얼러는 대상과 tcp 수준 연결을 설정합니다.

func (*Dialer) Dial

func (d *Dialer) Dial(network, address string) (net.Conn, error)

Dial connects to the address on the named network. It waits if needed not to exceed connectionsRateLimitingCount. 다이얼은 명명된 네트워크의 주소에 연결합니다. 필요하면 connectionsRateLimitingCount를 초과하지 않도록 기다립니다.

func (*Dialer) DialContext

func (d *Dialer) DialContext(ctx context.Context, network, address string) (net.Conn, error)

DialContext connects to the address on the named network using the provided context. DialContext 는 제공된 컨텍스트를 사용하여 명명된 네트워크의 주소에 연결합니다. It waits if needed not to exceed connectionsRateLimitingCount. 필요하면 connectionsRateLimitingCount 를 초과하지 않도록 기다립니다.

type ForwardingPolicy

type ForwardingPolicy int

ForwardingPolicy is an enum indicating to whom we should send a message ForwardingPolicy는 누구에게 메시지를 보내야 하는지를 나타내는 열거형입니다.

누구에게 메시지를 보내야하는지 나타내는 enum값
0: 보내지 않음
1: 이메시지를 보낸 피어와의 연결을 해제
2: 전송자를 제외한 나머지 모드에게 전달
3: 센더에게 응답
const (
	// Ignore - discard (don't forward)
	// 무시 - 폐기(전달하지 않음)
	Ignore ForwardingPolicy = iota

	// Disconnect - disconnect from the peer that sent this message
	// Disconnect - 이 메시지를 보낸 피어와의 연결을 끊습니다.
	Disconnect

	// Broadcast - forward to everyone (except the sender)
	// 브로드캐스트 - 모든 사람에게 전달(발신자 제외)
	Broadcast

	// Respond - reply to the sender
	// 응답 - 보낸 사람에게 응답
	Respond
)

type GossipNode

type GossipNode interface {
	Address() (string, bool)
	Broadcast(ctx context.Context, tag protocol.Tag, data []byte, wait bool, except Peer) error
	BroadcastArray(ctx context.Context, tag []protocol.Tag, data [][]byte, wait bool, except Peer) error
	Relay(ctx context.Context, tag protocol.Tag, data []byte, wait bool, except Peer) error
	RelayArray(ctx context.Context, tag []protocol.Tag, data [][]byte, wait bool, except Peer) error
	Disconnect(badnode Peer)
	DisconnectPeers()
	Ready() chan struct{}

	// RegisterHTTPHandler path accepts gorilla/mux path annotations
	// RegisterHTTPHandler 경로는 gorilla/mux 경로 주석을 허용합니다.
	RegisterHTTPHandler(path string, handler http.Handler)

	// RequestConnectOutgoing asks the system to actually connect to peers.
	// RequestConnectOutgoing은 시스템에 실제로 피어에 연결하도록 요청합니다.
	// `replace` optionally drops existing connections before making new ones.
	// `replace`는 새 연결을 만들기 전에 선택적으로 기존 연결을 삭제합니다.
	// `quit` chan allows cancellation. TODO: use `context`
	/*
		시스템에게 피어들과 연결해달라고 요청하는 함수
		replace가 TRUE면 연결 시 기존에 연결되었던 피어들의 정보를 삭제한다.
		quit채널로 취소할 수 있다(?)
	*/
	// `quit` chan은 취소를 허용합니다. TODO: `컨텍스트 사용
	RequestConnectOutgoing(replace bool, quit <-chan struct{})

	// Get a list of Peers we could potentially send a direct message to.
	// 잠재적으로 다이렉트 메시지를 보낼 수 있는 피어 목록을 가져옵니다.
	/*
		직접적으로 메시지를 보낼 수 있는 피어배열리스트 정보를 조회한다.
	*/
	GetPeers(options ...PeerOption) []Peer

	// Start threads, listen on sockets.
	/*
		쓰레드를 시작한다. 소켓연결을 기다린다.
	*/
	// 스레드를 시작하고 소켓에서 수신 대기합니다.
	Start()

	// Close sockets. Stop threads.
	// 소켓을 닫습니다. 스레드를 중지합니다.
	Stop()

	// RegisterHandlers adds to the set of given message handlers.
	// RegisterHandlers는 주어진 메시지 핸들러 세트에 추가합니다.
	RegisterHandlers(dispatch []TaggedMessageHandler)

	// ClearHandlers deregisters all the existing message handlers.
	// ClearHandlers는 기존의 모든 메시지 핸들러를 등록 취소합니다.
	ClearHandlers()

	// GetRoundTripper returns a Transport that would limit the number of outgoing connections.
	// GetRoundTripper는 나가는 연결 수를 제한하는 Transport를 반환합니다.
	GetRoundTripper() http.RoundTripper

	// OnNetworkAdvance notifies the network library that the agreement protocol was able to make a notable progress.
	// this is the only indication that we have that we haven't formed a clique, where all incoming messages
	// arrive very quickly, but might be missing some votes.
	// OnNetworkAdvance는 합의 프로토콜이 주목할 만한 진전을 이룰 수 있었음을 네트워크 라이브러리에 알립니다.
	// 이것은 우리가 파벌을 형성하지 않았다는 유일한 표시입니다.
	// 매우 빨리 도착하지만 일부 투표가 누락될 수 있습니다.
	// The usage of this call is expected to have similar characteristics as with a watchdog timer.
	// 이 호출의 사용은 워치독 타이머와 유사한 특성을 가질 것으로 예상됩니다.
	OnNetworkAdvance()

	// GetHTTPRequestConnection returns the underlying connection for the given request.
	// GetHTTPRequestConnection은 주어진 요청에 대한 기본 연결을 반환합니다.
	// Note that the request must be the same request that was provided to the http handler ( or provide a fallback Context() to that )
	// 요청은 http 핸들러에 제공된 것과 동일한 요청이어야 합니다(또는 이에 대한 대체 Context()를 제공해야 함).
	GetHTTPRequestConnection(request *http.Request) (conn net.Conn)

	// RegisterMessageInterest notifies the network library that this node wants to receive messages with the specified tag.
	// RegisterMessageInterest는 이 노드가 지정된 태그가 있는 메시지를 수신하기를 원한다는 것을 네트워크 라이브러리에 알립니다.
	// This will cause this node to send corresponding MsgOfInterest notifications to any newly connecting peers.
	// 이것은 이 노드가 대응하는 MsgOfInterest 알림을 새로 연결하는 피어에게 보내도록 합니다.
	// This should be called before the network is started.
	// 이것은 네트워크가 시작되기 전에 호출되어야 합니다.
	RegisterMessageInterest(protocol.Tag) error

	// SubstituteGenesisID substitutes the "{genesisID}" with their network-specific genesisID.
	// SubstituteGenesisID는 "{genesisID}"를 네트워크별 genesisID로 대체합니다.
	SubstituteGenesisID(rawURL string) string

	// GetPeerData returns a value stored by SetPeerData
	// GetPeerData는 SetPeerData에 의해 저장된 값을 반환합니다.
	GetPeerData(peer Peer, key string) interface{}

	// SetPeerData attaches a piece of data to a peer.
	// SetPeerData는 데이터 조각을 피어에 연결합니다.
	// Other services inside go-algorand may attach data to a peer that gets garbage collected when the peer is closed.
	// go-algorand 내부의 다른 서비스는 피어가 닫힐 때 수집되는 가비지 데이터를 피어에 연결할 수 있습니다.
	SetPeerData(peer Peer, key string, value interface{})
}

GossipNode represents a node in the gossip network GossipNode는 가십 네트워크의 노드를 나타냅니다.

func NewWebsocketGossipNode

func NewWebsocketGossipNode(log logging.Logger, config config.Local, phonebookAddresses []string, genesisID string, networkID protocol.NetworkID) (gn GossipNode, err error)

NewWebsocketGossipNode constructs a websocket network node and returns it as a GossipNode interface implementation NewWebsocketGossipNode는 웹 소켓 네트워크 노드를 구성하고 GossipNode 인터페이스 구현으로 반환합니다.

type HTTPPeer

type HTTPPeer interface {
	GetAddress() string
	GetHTTPClient() *http.Client
}

HTTPPeer is what the opaque Peer might be. HTTPPeer는 불투명한 Peer일 수 있습니다. If you get an opaque Peer handle from a GossipNode, maybe try a .(HTTPPeer) type assertion on it. GossipNode에서 불투명한 피어 핸들을 얻은 경우 .(HTTPPeer) 유형 어설션(:역설,주장)을 시도할 수 있습니다.

type HandlerFunc

type HandlerFunc func(message IncomingMessage) OutgoingMessage

HandlerFunc represents an implemenation of the MessageHandler interface HandlerFunc는 MessageHandler 인터페이스의 구현을 나타냅니다.

func (HandlerFunc) Handle

func (f HandlerFunc) Handle(message IncomingMessage) OutgoingMessage

Handle implements MessageHandler.Handle, calling the handler with the IncomingKessage and returning the OutgoingMessage 핸들은 MessageHandler.Handle을 구현하여 IncomingKessage로 핸들러를 호출하고 OutgoingMessage를 반환합니다.

type IncomingMessage

type IncomingMessage struct {
	Sender Peer
	Tag    Tag
	Data   []byte
	Err    error
	Net    GossipNode

	// Received is time.Time.UnixNano()
	// 수신은 time.Time.UnixNano()
	Received int64
	// contains filtered or unexported fields
}

IncomingMessage represents a message arriving from some peer in our p2p network IncomingMessage는 p2p 네트워크의 일부 피어에서 도착하는 메시지를 나타냅니다.

p2p네트워크의 다른 피어가 전송한 메시지이다.

type LimitedReaderSlurper

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

LimitedReaderSlurper collects bytes from an io.Reader, but stops if a limit is reached. LimitedReaderSlurper는 io.Reader에서 바이트를 수집하지만 제한에 도달하면 중지합니다.

func MakeLimitedReaderSlurper

func MakeLimitedReaderSlurper(baseAllocation, maxAllocation uint64) *LimitedReaderSlurper

MakeLimitedReaderSlurper creates a LimitedReaderSlurper instance with the provided base and max memory allocations. MakeLimitedReaderSlurper는 제공된 기본 및 최대 메모리 할당으로 LimitedReaderSlurper 인스턴스를 생성합니다.

func (*LimitedReaderSlurper) Bytes

func (s *LimitedReaderSlurper) Bytes() []byte

Bytes returns a copy of all the collected data Bytes는 수집된 모든 데이터의 복사본을 반환합니다.

func (*LimitedReaderSlurper) Read

func (s *LimitedReaderSlurper) Read(reader io.Reader) error

Read does repeated Read()s on the io.Reader until it gets io.EOF. Returns underlying error or ErrIncomingMsgTooLarge if limit reached. Returns a nil error if the underlying io.Reader returned io.EOF. Read는 io.EOF가 될 때까지 io.Reader에서 Read()를 반복합니다. 한계에 도달하면 기본 오류 또는 ErrIncomingMsgTooLarge를 반환합니다. 기본 io.Reader가 io.EOF를 반환하면 nil 오류를 반환합니다.

func (*LimitedReaderSlurper) Reset

func (s *LimitedReaderSlurper) Reset()

Reset clears the buffered data 재설정은 버퍼링된 데이터를 지웁니다.

func (*LimitedReaderSlurper) Size

func (s *LimitedReaderSlurper) Size() (size uint64)

Size returs the current total size of contained chunks read from io.Reader Size는 io.Reader에서 읽은 포함된 청크의 현재 총 크기를 반환합니다.

type MessageHandler

type MessageHandler interface {
	Handle(message IncomingMessage) OutgoingMessage
}

====== 멀티플렉서 ====== MessageHandler takes a IncomingMessage (e.g., vote, transaction), processes it, and returns what (if anything) to send to the network in response. MessageHandler는 IncomingMessage(예: 투표, 트랜잭션)를 받아 처리하고 응답으로 네트워크에 보낼 내용(있는 경우)을 반환합니다. The ForwardingPolicy field of the returned OutgoingMessage indicates whether to reply directly to the sender (unicast), propagate to everyone except the sender (broadcast), or do nothing (ignore). 반환된 OutgoingMessage의 ForwardingPolicy 필드는 보낸 사람에게 직접 회신할지(유니캐스트), 보낸 사람을 제외한 모든 사람에게 전파할지(브로드캐스트), 아무 작업도 수행하지 않을(무시) 여부를 나타냅니다. MessageHandler takes a IncomingMessage (e.g., vote, transaction), processes it, and returns what (if anything) to send to the network in response. The ForwardingPolicy field of the returned OutgoingMessage indicates whether to reply directly to the sender (unicast), propagate to everyone except the sender (broadcast), or do nothing (ignore).

IncomingMessage을 받아서 처리하고 응답을 네트워크로 전송한다.
OutgoingMessage의 ForwardingPolicy필드는 센더에게 직접 응답할것인디(unicast) sender를 제외한 모두에게 응답할 것인디(broascast)
혹은 아무것도 하지 않을 것인지를 나타낸다.

type Multiplexer

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

Multiplexer is a message handler that sorts incoming messages by Tag and passes them along to the relevant message handler for that type of message. Multiplexer는 들어오는 메시지를 태그별로 분류하고 해당 메시지 유형에 대한 관련 메시지 처리기로 전달하는 메시지 처리기입니다. Multiplexer is a message handler that sorts incoming messages by Tag and passes them along to the relevant message handler for that type of message.

Tag에 따라 인커밍 메시지를 저장하는 핸들러이다. 메시지들을 타입에 따라 관련된 메시지 핸들러에게 전달한다.

func MakeMultiplexer

func MakeMultiplexer(log logging.Logger) *Multiplexer

MakeMultiplexer creates an empty Multiplexer MakeMultiplexer는 빈 멀티플렉서를 생성합니다.

func (*Multiplexer) ClearHandlers

func (m *Multiplexer) ClearHandlers(excludeTags []Tag)

ClearHandlers deregisters all the existing message handlers other than the one provided in the excludeTags list ClearHandlers는 excludeTags 목록에 제공된 것 이외의 모든 기존 메시지 핸들러를 등록 취소합니다.

func (*Multiplexer) Handle

Handle is the "input" side of the multiplexer. It dispatches the message to the previously defined handler. 핸들은 멀티플렉서의 "입력" 측입니다. 이전에 정의된 핸들러에 메시지를 전달합니다.

func (*Multiplexer) RegisterHandlers

func (m *Multiplexer) RegisterHandlers(dispatch []TaggedMessageHandler)

RegisterHandlers registers the set of given message handlers. RegisterHandlers는 주어진 메시지 핸들러 세트를 등록합니다.

type NetPrioScheme

type NetPrioScheme interface {
	NewPrioChallenge() string
	MakePrioResponse(challenge string) []byte
	VerifyPrioResponse(challenge string, response []byte) (basics.Address, error)
	GetPrioWeight(addr basics.Address) uint64
}

NetPrioScheme is an implementation of network connection priorities based on a challenge-response protocol. NetPrioScheme은 시도-응답 프로토콜을 기반으로 하는 네트워크 연결 우선 순위의 구현입니다.

type OutgoingMessage

type OutgoingMessage struct {
	Action  ForwardingPolicy
	Tag     Tag
	Payload []byte
	Topics  Topics
}

OutgoingMessage represents a message we want to send. OutgoingMessage는 보내려는 메시지를 나타냅니다.

보내고 싶은 메시지이다.

func Propagate

func Propagate(msg IncomingMessage) OutgoingMessage

====== ====== Propagate is a convenience function to save typing in the common case of a message handler telling us to propagate an incoming message "return network.Propagate(msg)" instead of "return network.OutgoingMsg{network.Broadcast, msg.Tag, msg.Data}" Propagate는 "return network.OutgoingMsg{network.Broadcast, msg.Tag" 대신 "return network.Propagate(msg)"가 들어오는 메시지를 전파하도록 지시하는 메시지 처리기의 일반적인 경우 입력을 저장하는 편리한 기능입니다. msg.Data}"

type Peer

type Peer interface{}

Peer opaque interface for referring to a neighbor in the network 네트워크에서 이웃을 참조하기 위한 피어 불투명 인터페이스

type PeerOption

type PeerOption int

PeerOption allows users to specify a subset of peers to query PeerOption을 사용하면 사용자가 쿼리할 피어의 하위 집합을 지정할 수 있습니다.

const (
	// PeersConnectedOut specifies all peers with outgoing connections
	// PeersConnectedOut은 나가는 연결이 있는 모든 피어를 지정합니다.
	PeersConnectedOut PeerOption = iota
	// PeersConnectedIn specifies all peers with inbound connections
	// PeersConnectedIn은 인바운드 연결이 있는 모든 피어를 지정합니다.
	PeersConnectedIn PeerOption = iota
	// PeersPhonebookRelays specifies all relays in the phonebook
	// PeersPhonebookRelays는 전화번호부의 모든 릴레이를 지정합니다.
	PeersPhonebookRelays PeerOption = iota
	// PeersPhonebookArchivers specifies all archivers in the phonebook
	// PeersPhonebookArchivers는 전화번호부의 모든 아카이버를 지정합니다.
	PeersPhonebookArchivers PeerOption = iota
)

type PhoneBookEntryRoles

type PhoneBookEntryRoles int

PhoneBookEntryRoles defines the roles that a single entry on the phonebook can take. currently, we have two roles : relay role and archiver role, which are mutually exclusive. PhoneBookEntryRoles는 전화번호부의 단일 항목이 취할 수 있는 역할을 정의합니다. 현재 두 가지 역할이 있습니다. 즉, 릴레이 역할과 아카이버 역할은 상호 배타적입니다.

type Phonebook

type Phonebook interface {
	// GetAddresses(N) returns up to N addresses, but may return fewer
	// GetAddresses(N)은 최대 N개의 주소를 반환하지만 더 적은 수를 반환할 수 있습니다.
	GetAddresses(n int, role PhoneBookEntryRoles) []string

	// UpdateRetryAfter updates the retry-after field for the entries matching the given address
	// UpdateRetryAfter는 주어진 주소와 일치하는 항목에 대한 retry-after 필드를 업데이트합니다.
	UpdateRetryAfter(addr string, retryAfter time.Time)

	// GetConnectionWaitTime will calculate and return the wait time to prevent exceeding connectionsRateLimitingCount.
	// The connection should be established when the waitTime is 0.
	// It will register a provisional next connection time when the waitTime is 0.
	// The provisional time should be updated after the connection with UpdateConnectionTime\
	// GetConnectionWaitTime은 connectionsRateLimitingCount 초과를 방지하기 위해 대기 시간을 계산하고 반환합니다.
	// waitTime이 0일 때 연결이 설정되어야 합니다.
	// waitTime이 0일 때 잠정적으로 다음 연결 시간을 등록합니다.
	// UpdateConnectionTime과 연결한 후 임시 시간을 업데이트해야 합니다.
	GetConnectionWaitTime(addr string) (addrInPhonebook bool,
		waitTime time.Duration, provisionalTime time.Time)

	// UpdateConnectionTime will update the provisional connection time.
	// Returns true of the addr was in the phonebook
	// UpdateConnectionTime은 임시 연결 시간을 업데이트합니다.
	// addr가 전화번호부에 있었다면 true를 반환합니다.
	UpdateConnectionTime(addr string, provisionalTime time.Time) bool

	// ReplacePeerList merges a set of addresses with that passed in for networkName
	// new entries in dnsAddresses are being added
	// existing items that aren't included in dnsAddresses are being removed
	// matching entries don't change
	// ReplacePeerList는 networkName에 대해 전달된 주소 세트를 병합합니다.
	// dnsAddresses의 새 항목이 추가되고 있습니다.
	// dnsAddresses에 포함되지 않은 기존 항목은 제거 중입니다.
	// 일치하는 항목은 변경되지 않음
	ReplacePeerList(dnsAddresses []string, networkName string, role PhoneBookEntryRoles)

	// ExtendPeerList adds unique addresses to this set of addresses
	// ExtendPeerList는 이 주소 집합에 고유 주소를 추가합니다.
	ExtendPeerList(more []string, networkName string, role PhoneBookEntryRoles)
}

Phonebook stores or looks up addresses of nodes we might contact 전화번호부는 우리가 접촉할 수 있는 노드의 주소를 저장하거나 조회합니다.

func MakePhonebook

func MakePhonebook(connectionsRateLimitingCount uint,
	connectionsRateLimitingWindow time.Duration) Phonebook

MakePhonebook creates phonebookImpl with the passed configuration values MakePhonebook은 전달된 구성 값으로 phonebookImpl을 생성합니다.

type RequestLogger

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

RequestLogger is a middleware helps logging all the incoming http requests. RequestLogger는 들어오는 모든 http 요청을 기록하는 데 도움이 되는 미들웨어입니다. The intended use is to place it at the bottom of the http processing. 의도된 용도는 http 처리의 맨 아래에 배치하는 것입니다. It will capture the status codes set by the upstream handlers and write the request info/response to the logger. 업스트림 핸들러가 설정한 상태 코드를 캡처하고 요청 정보/응답을 로거에 씁니다.

func (*RequestLogger) ServeHTTP

func (rl *RequestLogger) ServeHTTP(writer http.ResponseWriter, request *http.Request)

this is the http entry point for the request logger. 이것은 요청 로거의 http 진입점입니다.

func (*RequestLogger) SetStatusCode

func (rl *RequestLogger) SetStatusCode(writer http.ResponseWriter, statusCode int)

SetStatusCode sets the status code of a given response writer without writing it to the underlaying writer object. SetStatusCode는 기본 작성기 개체에 쓰지 않고 주어진 응답 작성기의 상태 코드를 설정합니다.

type RequestTracker

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

RequestTracker tracks the incoming request connections RequestTracker는 들어오는 요청 연결을 추적합니다.

func (*RequestTracker) Accept

func (rt *RequestTracker) Accept() (conn net.Conn, err error)

Accept waits for and returns the next connection to the listener. Accept는 리스너에 대한 다음 연결을 기다리고 반환합니다.

func (*RequestTracker) Addr

func (rt *RequestTracker) Addr() net.Addr

Addr returns the listener's network address. Addr은 리스너의 네트워크 주소를 반환합니다.

func (*RequestTracker) Close

func (rt *RequestTracker) Close() error

Close closes the listener. Any blocked Accept operations will be unblocked and return errors. 닫기는 리스너를 닫습니다. 차단된 모든 수락 작업은 차단 해제되고 오류를 반환합니다.

func (*RequestTracker) GetRequestConnection

func (rt *RequestTracker) GetRequestConnection(request *http.Request) net.Conn

GetRequestConnection return the underlying connection for the given request GetRequestConnection은 주어진 요청에 대한 기본 연결을 반환합니다.

func (*RequestTracker) GetTrackedRequest

func (rt *RequestTracker) GetTrackedRequest(request *http.Request) (trackedRequest *TrackerRequest)

GetTrackedRequest return the tracked request GetTrackedRequest는 추적된 요청을 반환합니다.

func (*RequestTracker) Listener

func (rt *RequestTracker) Listener(listener net.Listener) net.Listener

Listener initialize the underlaying listener, and return the request tracker wrapping listener 리스너는 기본 리스너를 초기화하고 리스너를 래핑하는 요청 추적기를 반환합니다.

func (*RequestTracker) ServeHTTP

func (rt *RequestTracker) ServeHTTP(response http.ResponseWriter, request *http.Request)

type Response

type Response struct {
	Topics Topics
}

Response is the structure holding the response from the server Response는 서버의 응답을 담고 있는 구조체입니다.

type Tag

type Tag = protocol.Tag

Tag is a short string (2 bytes) marking a type of message 태그는 메시지 유형을 표시하는 짧은 문자열(2바이트)입니다.

type TaggedMessageHandler

type TaggedMessageHandler struct {
	Tag
	MessageHandler
}

TaggedMessageHandler receives one type of broadcast messages TaggedMessageHandler는 한 가지 유형의 브로드캐스트 메시지를 수신합니다.

broadcast 타입의 메시지를 받는다. 이 핸들러가 처리하는 메시지는 모두 브로드캐스팅을 하는건가?

type Topic

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

Topic is a key-value pair 토픽은 키-값 쌍입니다.

func MakeTopic

func MakeTopic(key string, data []byte) Topic

MakeTopic Creates a Topic MakeTopic은 토픽을 생성합니다.

type Topics

type Topics []Topic

Topics is an array of type Topic The maximum number of topics allowed is 32 Each topic key can be 64 characters long and cannot be size 0 토픽은 토픽 유형의 배열입니다. 허용되는 최대 주제 수는 32개입니다. 각 토픽 키는 64자일 수 있으며 크기가 0일 수 없습니다.

func UnmarshallTopics

func UnmarshallTopics(buffer []byte) (ts Topics, err error)

UnmarshallTopics unmarshalls the topics from the byte array UnmarshallTopics는 바이트 배열에서 토픽을 비정렬화합니다.

func (*Topics) GetValue

func (ts *Topics) GetValue(key string) (val []byte, found bool)

GetValue returns the value of the key if the key is found in the topics GetValue는 토픽에서 키가 발견되면 키의 값을 반환합니다.

func (Topics) MarshallTopics

func (ts Topics) MarshallTopics() (b []byte)

MarshallTopics serializes the topics into a byte array MarshallTopics는 주제를 바이트 배열로 직렬화합니다.

type TrackerRequest

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

TrackerRequest hold the tracking data associated with a single request. TrackerRequest는 단일 요청과 관련된 추적 데이터를 보유합니다.

type UnicastPeer

type UnicastPeer interface {
	GetAddress() string
	// Unicast sends the given bytes to this specific peer. Does not wait for message to be sent.
	// 유니캐스트는 주어진 바이트를 이 특정 피어로 보냅니다. 메시지가 전송될 때까지 기다리지 않습니다.
	Unicast(ctx context.Context, data []byte, tag protocol.Tag) error
	// Version returns the matching version from network.SupportedProtocolVersions
	// 버전은 network.SupportedProtocolVersions에서 일치하는 버전을 반환합니다.
	Version() string
	Request(ctx context.Context, tag Tag, topics Topics) (resp *Response, e error)
	Respond(ctx context.Context, reqMsg IncomingMessage, topics Topics) (e error)
}

UnicastPeer is another possible interface for the opaque Peer. UnicastPeer는 불투명 피어에 대한 또 다른 가능한 인터페이스입니다. It is possible that we can only initiate a connection to a peer over websockets. 웹 소켓을 통해서만 피어에 대한 연결을 시작할 수 있습니다.

type WebsocketNetwork

type WebsocketNetwork struct {
	GenesisID string
	NetworkID protocol.NetworkID
	RandomID  string
	// contains filtered or unexported fields
}

func NewWebsocketNetwork

func NewWebsocketNetwork(log logging.Logger, config config.Local, phonebookAddresses []string, genesisID string, networkID protocol.NetworkID) (wn *WebsocketNetwork, err error)

NewWebsocketNetwork constructor for websockets based gossip network 웹 소켓 기반 가십 네트워크용 NewWebsocketNetwork 생성자

func (*WebsocketNetwork) Address

func (wn *WebsocketNetwork) Address() (string, bool)

Address returns a string and whether that is a 'final' address or guessed. 주소는 문자열과 그것이 '최종' 주소인지 추측된 주소인지를 반환합니다. Part of GossipNode interface GossipNode 인터페이스의 일부

func (*WebsocketNetwork) Broadcast

func (wn *WebsocketNetwork) Broadcast(ctx context.Context, tag protocol.Tag, data []byte, wait bool, except Peer) error

Broadcast sends a message. 브로드캐스트는 메시지를 보냅니다. If except is not nil then we will not send it to that neighboring Peer. 만약 except가 nil이 아니라면 우리는 그것을 이웃 Peer로 보내지 않을 것입니다. if wait is true then the call blocks until the packet has actually been sent to all neighbors. wait가 참이면 패킷이 모든 이웃에게 실제로 전송될 때까지 호출이 차단됩니다.

func (*WebsocketNetwork) BroadcastArray

func (wn *WebsocketNetwork) BroadcastArray(ctx context.Context, tags []protocol.Tag, data [][]byte, wait bool, except Peer) error

BroadcastArray sends an array of messages. BroadcastArray는 메시지 배열을 보냅니다. If except is not nil then we will not send it to that neighboring Peer. 만약 except가 nil이 아니라면 우리는 그것을 이웃 Peer로 보내지 않을 것입니다. if wait is true then the call blocks until the packet has actually been sent to all neighbors. wait가 참이면 패킷이 모든 이웃에게 실제로 전송될 때까지 호출이 차단됩니다. TODO: add `priority` argument so that we don't have to guess it based on tag

func (*WebsocketNetwork) ClearHandlers

func (wn *WebsocketNetwork) ClearHandlers()

ClearHandlers deregisters all the existing message handlers. ClearHandlers는 기존의 모든 메시지 핸들러를 등록 취소합니다.

func (*WebsocketNetwork) Disconnect

func (wn *WebsocketNetwork) Disconnect(node Peer)

Disconnect from a peer, probably due to protocol errors. 프로토콜 오류로 인해 피어에서 연결을 끊습니다.

func (*WebsocketNetwork) DisconnectPeers

func (wn *WebsocketNetwork) DisconnectPeers()

DisconnectPeers shuts down all connections DisconnectPeers는 모든 연결을 종료합니다.

func (*WebsocketNetwork) GetHTTPRequestConnection

func (wn *WebsocketNetwork) GetHTTPRequestConnection(request *http.Request) (conn net.Conn)

GetHTTPRequestConnection returns the underlying connection for the given request. GetHTTPRequestConnection은 주어진 요청에 대한 기본 연결을 반환합니다. Note that the request must be the same request that was provided to the http handler ( or provide a fallback Context() to that ) 요청은 http 핸들러에 제공된 것과 동일한 요청이어야 합니다(또는 이에 대한 대체 Context()를 제공해야 함). if the provided request has no associated connection, it returns nil. ( this should not happen for any http request that was registered by WebsocketNetwork ) 제공된 요청에 연결된 연결이 없으면 nil을 반환합니다. (WebsocketNetwork에 의해 등록된 모든 http 요청에 대해서는 발생하지 않아야 함)

func (*WebsocketNetwork) GetPeerData

func (wn *WebsocketNetwork) GetPeerData(peer Peer, key string) interface{}

GetPeerData returns the peer data associated with a particular key. GetPeerData는 특정 키와 연결된 피어 데이터를 반환합니다.

func (*WebsocketNetwork) GetPeers

func (wn *WebsocketNetwork) GetPeers(options ...PeerOption) []Peer

GetPeers returns a snapshot of our Peer list, according to the specified options. GetPeers는 지정된 옵션에 따라 피어 목록의 스냅샷을 반환합니다. Peers may be duplicated and refer to the same underlying node. 피어는 중복될 수 있으며 동일한 기본 노드를 참조할 수 있습니다.

func (*WebsocketNetwork) GetRoundTripper

func (wn *WebsocketNetwork) GetRoundTripper() http.RoundTripper

GetRoundTripper returns an http.Transport that limits the number of connection to comply with connectionsRateLimitingCount. GetRoundTripper는 connectionsRateLimitingCount 를 준수하도록 연결 수를 제한하는 http.Transport를 반환합니다.

func (*WebsocketNetwork) NumPeers

func (wn *WebsocketNetwork) NumPeers() int

NumPeers returns number of peers we connect to (all peers incoming and outbound). NumPeers는 우리가 연결하는 피어의 수를 반환합니다(모든 피어 수신 및 발신).

func (*WebsocketNetwork) OnNetworkAdvance

func (wn *WebsocketNetwork) OnNetworkAdvance()

OnNetworkAdvance notifies the network library that the agreement protocol was able to make a notable progress. OnNetworkAdvance는 합의 프로토콜이 주목할 만한 진전을 이룰 수 있었음을 네트워크 라이브러리에 알립니다. this is the only indication that we have that we haven't formed a clique, where all incoming messages arrive very quickly, but might be missing some votes. 이것은 모든 수신 메시지가 매우 빠르게 도착하지만 일부 투표가 누락될 수 있는 파벌을 형성하지 않았다는 유일한 표시입니다. The usage of this call is expected to have similar 이 호출의 사용법은 비슷할 것으로 예상됩니다. characteristics as with a watchdog timer. 감시 타이머와 같은 특성.

func (*WebsocketNetwork) PublicAddress

func (wn *WebsocketNetwork) PublicAddress() string

PublicAddress what we tell other nodes to connect to. 다른 노드에 연결하도록 지시하는 PublicAddress입니다. Might be different than our locally perceived network address due to NAT/etc. NAT/등으로 인해 로컬에서 인식되는 네트워크 주소와 다를 수 있습니다. Returns config "PublicAddress" if available, otherwise local addr. 사용 가능한 경우 구성 "PublicAddress"를 반환하고, 그렇지 않으면 로컬 주소를 반환합니다.

func (*WebsocketNetwork) Ready

func (wn *WebsocketNetwork) Ready() chan struct{}

Ready returns a chan that will be closed when we have a minimum number of peer connections active Ready는 최소한의 피어 연결이 활성화되었을 때 닫힐 chan을 반환합니다.

func (*WebsocketNetwork) RegisterHTTPHandler

func (wn *WebsocketNetwork) RegisterHTTPHandler(path string, handler http.Handler)

RegisterHTTPHandler path accepts gorilla/mux path annotations RegisterHTTPHandler 경로는 gorilla/mux 경로 주석을 허용합니다.

func (*WebsocketNetwork) RegisterHandlers

func (wn *WebsocketNetwork) RegisterHandlers(dispatch []TaggedMessageHandler)

RegisterHandlers registers the set of given message handlers. RegisterHandlers는 주어진 메시지 핸들러 세트를 등록합니다.

func (*WebsocketNetwork) RegisterMessageInterest

func (wn *WebsocketNetwork) RegisterMessageInterest(t protocol.Tag) error

RegisterMessageInterest notifies the network library that this node wants to receive messages with the specified tag. RegisterMessageInterest는 이 노드가 지정된 태그가 있는 메시지를 수신하기를 원한다는 것을 네트워크 라이브러리에 알립니다. This will cause this node to send corresponding MsgOfInterest notifications to any newly connecting peers. 이것은 이 노드가 대응하는 MsgOfInterest 알림을 새로 연결하는 피어에게 보내도록 합니다. This should be called before the network is started. 이것은 네트워크가 시작되기 전에 호출되어야 합니다.

func (*WebsocketNetwork) Relay

func (wn *WebsocketNetwork) Relay(ctx context.Context, tag protocol.Tag, data []byte, wait bool, except Peer) error

Relay message

func (*WebsocketNetwork) RelayArray

func (wn *WebsocketNetwork) RelayArray(ctx context.Context, tags []protocol.Tag, data [][]byte, wait bool, except Peer) error

RelayArray relays array of messages RelayArray는 메시지 배열을 릴레이합니다.

func (*WebsocketNetwork) RequestConnectOutgoing

func (wn *WebsocketNetwork) RequestConnectOutgoing(replace bool, quit <-chan struct{})

RequestConnectOutgoing tries to actually do the connect to new peers. RequestConnectOutgoing 은 실제로 새 피어에 연결을 시도합니다. `replace` drop all connections first and find new peers. `replace`는 먼저 모든 연결을 삭제하고 새 피어를 찾습니다.

func (*WebsocketNetwork) ServeHTTP

func (wn *WebsocketNetwork) ServeHTTP(response http.ResponseWriter, request *http.Request)

ServerHTTP handles the gossip network functions over websockets ServerHTTP는 웹 소켓을 통해 가십 네트워크 기능을 처리합니다. keep serving request

func (*WebsocketNetwork) SetPeerData

func (wn *WebsocketNetwork) SetPeerData(peer Peer, key string, value interface{})

SetPeerData sets the peer data associated with a particular key. SetPeerData는 특정 키와 관련된 피어 데이터를 설정합니다.

func (*WebsocketNetwork) SetPrioScheme

func (wn *WebsocketNetwork) SetPrioScheme(s NetPrioScheme)

SetPrioScheme specifies the network priority scheme for a network node SetPrioScheme은 네트워크 노드에 대한 네트워크 우선 순위 체계를 지정합니다.

func (*WebsocketNetwork) Start

func (wn *WebsocketNetwork) Start()

Start makes network connections and threads 시작은 네트워크 연결 및 스레드를 만듭니다.

func (*WebsocketNetwork) Stop

func (wn *WebsocketNetwork) Stop()

Stop closes network connections and stops threads. Stop은 네트워크 연결을 닫고 스레드를 중지합니다. Stop blocks until all activity on this node is done. 이 노드의 모든 활동이 완료될 때까지 블록을 중지합니다.

func (*WebsocketNetwork) SubstituteGenesisID

func (wn *WebsocketNetwork) SubstituteGenesisID(rawURL string) string

SubstituteGenesisID substitutes the "{genesisID}" with their network-specific genesisID. SubstituteGenesisID는 "{genesisID}"를 네트워크별 genesisID로 대체합니다.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL