sys

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Jul 12, 2026 License: MIT Imports: 4 Imported by: 0

Documentation

Overview

Package sys is layer 0 of the nwep go binding, the raw cgo surface NWG0200.

it is a 1:1, unsafe, total translation of nwep.h and nwep_trust.h. every exported c symbol gets a thin wrapper here and nothing more, so the safe layers above can never become a feature ceiling NWG1000. c struct types cannot cross a cgo package boundary, so opaque handles are returned as unsafe.Pointer and the fixed value types as go arrays. secret key material is kept in c memory and never copied into the go heap so it can be wiped with Zeroize NWG0700. nobody is meant to enjoy this layer, reach for the nwep package instead.

Index

Constants

View Source
const (
	ErrConfigInvalid = int(C.NWEP_ERR_CONFIG_INVALID)
	ErrConfigMissing = int(C.NWEP_ERR_CONFIG_MISSING)

	ErrNetworkConnect = int(C.NWEP_ERR_NETWORK_CONNECT)
	ErrNetworkTimeout = int(C.NWEP_ERR_NETWORK_TIMEOUT)
	ErrNetworkClosed  = int(C.NWEP_ERR_NETWORK_CLOSED)
	ErrNetworkQUIC    = int(C.NWEP_ERR_NETWORK_QUIC)
	ErrNetworkTLS     = int(C.NWEP_ERR_NETWORK_TLS)

	ErrCryptoKeygen = int(C.NWEP_ERR_CRYPTO_KEYGEN)
	ErrCryptoRand   = int(C.NWEP_ERR_CRYPTO_RAND)
	ErrCryptoSign   = int(C.NWEP_ERR_CRYPTO_SIGN)
	ErrCryptoVerify = int(C.NWEP_ERR_CRYPTO_VERIFY)

	ErrCryptoFatalCert           = int(C.NWEP_ERR_CRYPTO_FATAL_CERT)
	ErrCryptoFatalNodeidMismatch = int(C.NWEP_ERR_CRYPTO_FATAL_NODEID_MISMATCH)
	ErrCryptoFatalChallenge      = int(C.NWEP_ERR_CRYPTO_FATAL_CHALLENGE)
	ErrCryptoFatalServerSig      = int(C.NWEP_ERR_CRYPTO_FATAL_SERVER_SIG)
	ErrCryptoFatalClientSig      = int(C.NWEP_ERR_CRYPTO_FATAL_CLIENT_SIG)

	ErrProtoInvalidMessage  = int(C.NWEP_ERR_PROTO_INVALID_MESSAGE)
	ErrProtoInvalidMethod   = int(C.NWEP_ERR_PROTO_INVALID_METHOD)
	ErrProtoInvalidHeader   = int(C.NWEP_ERR_PROTO_INVALID_HEADER)
	ErrProtoConnectRequired = int(C.NWEP_ERR_PROTO_CONNECT_REQUIRED)
	ErrProtoStreamReuse     = int(C.NWEP_ERR_PROTO_STREAM_REUSE)
	ErrProtoMaxStreams      = int(C.NWEP_ERR_PROTO_MAX_STREAMS)
	ErrProtoFlowControl     = int(C.NWEP_ERR_PROTO_FLOW_CONTROL)
	ErrProtoMessageTooLarge = int(C.NWEP_ERR_PROTO_MESSAGE_TOO_LARGE)

	ErrProtoFatalVersion = int(C.NWEP_ERR_PROTO_FATAL_VERSION)

	ErrIdentityGenerate = int(C.NWEP_ERR_IDENTITY_GENERATE)
	ErrIdentityMismatch = int(C.NWEP_ERR_IDENTITY_MISMATCH)
	ErrIdentityNotFound = int(C.NWEP_ERR_IDENTITY_NOT_FOUND)
	ErrIdentityRevoked  = int(C.NWEP_ERR_IDENTITY_REVOKED)

	ErrAppNotFound    = int(C.NWEP_ERR_APP_NOT_FOUND)
	ErrAppConflict    = int(C.NWEP_ERR_APP_CONFLICT)
	ErrAppRateLimited = int(C.NWEP_ERR_APP_RATE_LIMITED)
	ErrAppForbidden   = int(C.NWEP_ERR_APP_FORBIDDEN)

	ErrTrustInvalidEntry    = int(C.NWEP_ERR_TRUST_INVALID_ENTRY)
	ErrTrustInvalidAnchor   = int(C.NWEP_ERR_TRUST_INVALID_ANCHOR)
	ErrTrustStaleCheckpoint = int(C.NWEP_ERR_TRUST_STALE_CHECKPOINT)
	ErrTrustThreshold       = int(C.NWEP_ERR_TRUST_THRESHOLD)
	ErrTrustRevoked         = int(C.NWEP_ERR_TRUST_REVOKED)
	ErrTrustNoCheckpoint    = int(C.NWEP_ERR_TRUST_NO_CHECKPOINT)

	ErrTrustFatalEquivocation = int(C.NWEP_ERR_TRUST_FATAL_EQUIVOCATION)
	ErrTrustFatalLogCorrupt   = int(C.NWEP_ERR_TRUST_FATAL_LOG_CORRUPT)

	ErrInternal      = int(C.NWEP_ERR_INTERNAL)
	ErrInternalAlloc = int(C.NWEP_ERR_INTERNAL_ALLOC)
	ErrWouldBlock    = int(C.NWEP_ERR_WOULD_BLOCK)
)

the error codes, stable negative integers grouped by family NW130000.

View Source
const (
	MethodRead      = int(C.NWEP_METHOD_READ)
	MethodWrite     = int(C.NWEP_METHOD_WRITE)
	MethodUpdate    = int(C.NWEP_METHOD_UPDATE)
	MethodDelete    = int(C.NWEP_METHOD_DELETE)
	MethodHeartbeat = int(C.NWEP_METHOD_HEARTBEAT)
	MethodHead      = int(C.NWEP_METHOD_HEAD)
)

the request method codes NW040400.

View Source
const (
	StatusOk                  = int(C.NWEP_STATUS_OK)
	StatusCreated             = int(C.NWEP_STATUS_CREATED)
	StatusAccepted            = int(C.NWEP_STATUS_ACCEPTED)
	StatusNoContent           = int(C.NWEP_STATUS_NO_CONTENT)
	StatusPartialContent      = int(C.NWEP_STATUS_PARTIAL_CONTENT)
	StatusMoved               = int(C.NWEP_STATUS_MOVED)
	StatusNotModified         = int(C.NWEP_STATUS_NOT_MODIFIED)
	StatusBadRequest          = int(C.NWEP_STATUS_BAD_REQUEST)
	StatusUnauthorized        = int(C.NWEP_STATUS_UNAUTHORIZED)
	StatusForbidden           = int(C.NWEP_STATUS_FORBIDDEN)
	StatusNotFound            = int(C.NWEP_STATUS_NOT_FOUND)
	StatusNotAllowed          = int(C.NWEP_STATUS_NOT_ALLOWED)
	StatusConflict            = int(C.NWEP_STATUS_CONFLICT)
	StatusGone                = int(C.NWEP_STATUS_GONE)
	StatusTooLarge            = int(C.NWEP_STATUS_TOO_LARGE)
	StatusPreconditionFailed  = int(C.NWEP_STATUS_PRECONDITION_FAILED)
	StatusRangeNotSatisfiable = int(C.NWEP_STATUS_RANGE_NOT_SATISFIABLE)
	StatusRateLimited         = int(C.NWEP_STATUS_RATE_LIMITED)
	StatusError               = int(C.NWEP_STATUS_ERROR)
	StatusUnavailable         = int(C.NWEP_STATUS_UNAVAILABLE)
	StatusTimeout             = int(C.NWEP_STATUS_TIMEOUT)
	StatusNotImplemented      = int(C.NWEP_STATUS_NOT_IMPLEMENTED)
)

the status codes NW080000. use with nwep_status_str or nwep_message_get_status_code.

View Source
const (
	NodeIDSize  = C.NWEP_NODEID_SIZE
	PubKeySize  = C.NWEP_PUBKEY_SIZE
	PrivKeySize = C.NWEP_PRIVKEY_SIZE
)

the fixed byte sizes of the value types, taken from the header NW040200.

View Source
const (
	BLSPubkeySize    = int(C.NWEP_BLS_PUBKEY_SIZE)
	BLSSeckeySize    = int(C.NWEP_BLS_SECKEY_SIZE)
	BLSSignatureSize = int(C.NWEP_BLS_SIGNATURE_SIZE)
)

the bls12-381 key and signature sizes from the trust header NW150500.

View Source
const DeferSentinel = int(C.NWEP_DEFER)

DeferSentinel is NWEP_DEFER, the handler return that answers out of band later.

Variables

This section is empty.

Functions

func AddressGetPort

func AddressGetPort(a Address) uint16

AddressGetPort returns the udp port held in an address (nwep_address_get_port).

func AnchorFinishCheckpoint

func AnchorFinishCheckpoint(epoch uint64, merkleRoot [32]byte, logSize uint64, indices, sigs []byte, nPartials int, anchorBLSPks []byte, nAnchors int) ([]byte, int)

AnchorFinishCheckpoint aggregates partial signatures into a final checkpoint (nwep_anchor_finish_checkpoint).

indices is one byte per partial, sigs nPartials concatenated 96-byte signatures, anchorBLSPks nAnchors concatenated 48-byte keys.

func AnchorNodeCollectLogRoot

func AnchorNodeCollectLogRoot(node unsafe.Pointer, epoch uint64, serverRoot [32]byte, serverLogSize uint64, localRoot [32]byte) int

AnchorNodeCollectLogRoot records a server's reported log root for an epoch (nwep_anchor_node_collect_log_root).

func AnchorNodeCreate

func AnchorNodeCreate(pubkey, privkey, blsSecret [32]byte, blsPubkey [48]byte, shareIndex, collectionWindowMs uint64) unsafe.Pointer

AnchorNodeCreate allocates an anchor node from its keys and bls share (nwep_anchor_node_create).

func AnchorNodeDispatch

func AnchorNodeDispatch(node unsafe.Pointer, requesterNodeID [32]byte, anchorIDs []byte, nAnchors int, req, buf unsafe.Pointer, nowSecs int64) int

AnchorNodeDispatch answers a partial-signature request into buf, from a handler (nwep_anchor_node_dispatch).

func AnchorNodeFree

func AnchorNodeFree(node unsafe.Pointer)

AnchorNodeFree frees an anchor node (nwep_anchor_node_free).

func AnchorNodeProducePartialSig

func AnchorNodeProducePartialSig(node unsafe.Pointer, epoch uint64, merkleRoot [32]byte, logSize uint64) (index uint8, sig [96]byte, rc int)

AnchorNodeProducePartialSig produces this anchor's partial signature for a root (nwep_anchor_node_produce_partial_sig).

func AnchorRequestPartialSig

func AnchorRequestPartialSig(client unsafe.Pointer, epoch uint64, merkleRoot [32]byte, logSize uint64, peerBLSPubkey [48]byte) (index uint8, sig [96]byte, rc int)

AnchorRequestPartialSig asks a peer anchor for its partial signature over a client (nwep_anchor_request_partial_sig).

func BLSAggregate

func BLSAggregate(sigs []byte, n int) (sig [96]byte, rc int)

BLSAggregate aggregates n concatenated signatures into one (nwep_bls_aggregate).

func BLSKeygen

func BLSKeygen() (sk [32]byte, pk [48]byte, rc int)

BLSKeygen generates a bls secret and public key pair (nwep_bls_keygen).

func BLSSign

func BLSSign(sk [32]byte, msg []byte) (sig [96]byte, rc int)

BLSSign signs msg with a bls secret key, returning the 96-byte signature (nwep_bls_sign).

func BLSVerify

func BLSVerify(sig [96]byte, pk [48]byte, msg []byte) int

BLSVerify verifies a bls signature over msg under pk (nwep_bls_verify).

func BLSVerifyAggregate

func BLSVerifyAggregate(aggSig [96]byte, pks []byte, n int, msg []byte) int

BLSVerifyAggregate verifies an aggregate signature over msg under n public keys (nwep_bls_verify_aggregate).

func CacheClear

func CacheClear(cache unsafe.Pointer)

CacheClear drops every entry but keeps the cache allocated (nwep_cache_clear).

func CacheCreate

func CacheCreate(maxBytes, maxEntries int) unsafe.Pointer

CacheCreate allocates a response cache bounded by bytes and entries (nwep_cache_create).

func CacheFree

func CacheFree(cache unsafe.Pointer)

CacheFree frees a cache (nwep_cache_free).

func CacheGetSigned

func CacheGetSigned(cache unsafe.Pointer, method, path string, originPubkey [PubKeySize]byte, nowSecs uint64) (unsafe.Pointer, int)

CacheGetSigned fetches a still-fresh cached response, if present (nwep_cache_get_signed).

func CachePutSigned

func CachePutSigned(cache unsafe.Pointer, method, path string, resp unsafe.Pointer, originPubkey [PubKeySize]byte, nowSecs uint64) int

CachePutSigned stores a verified response keyed by method, path, and origin (nwep_cache_put_signed).

func CheckpointDecode

func CheckpointDecode(bytes []byte) (unsafe.Pointer, int)

CheckpointDecode decodes a checkpoint into an owned handle (nwep_checkpoint_decode).

func CheckpointFree

func CheckpointFree(cp unsafe.Pointer)

CheckpointFree frees a decoded checkpoint (nwep_checkpoint_free).

func CheckpointStaleness

func CheckpointStaleness(cp unsafe.Pointer, nowSecs int64) int

CheckpointStaleness returns how stale a checkpoint is at now_secs (nwep_checkpoint_staleness).

func CheckpointVerify

func CheckpointVerify(ts unsafe.Pointer, cpBytes []byte, nowSecs int64) int

CheckpointVerify checks a checkpoint against the store's anchors without adopting it (nwep_checkpoint_verify).

func CidShardID

func CidShardID(cid []byte) int

CidShardID returns which shard a connection id routes to (nwep_cid_shard_id).

func ClientClose

func ClientClose(client unsafe.Pointer)

ClientClose tears down the connection, frees it, and retires its hooks (nwep_client_close).

func ClientCompression

func ClientCompression(client unsafe.Pointer) int

ClientCompression reports whether the connection negotiated body compression (nwep_client_compression).

func ClientConnect

func ClientConnect(identity unsafe.Pointer, target [NodeIDSize]byte, addr Address) (unsafe.Pointer, int)

ClientConnect dials target_addr and runs the web/1 handshake, blocking (nwep_client_connect).

func ClientConnectAsync

func ClientConnectAsync(identity unsafe.Pointer, target [NodeIDSize]byte, addr Address) (unsafe.Pointer, int)

ClientConnectAsync starts a non-blocking connect, driven with ClientConnectPoll (nwep_client_connect_async).

func ClientConnectByNodeid

func ClientConnectByNodeid(identity unsafe.Pointer, target [NodeIDSize]byte, dht unsafe.Pointer, lookupTimeoutMs uint32) (unsafe.Pointer, int)

ClientConnectByNodeid resolves the target through the dht then connects (nwep_client_connect_by_nodeid).

func ClientConnectFd

func ClientConnectFd(identity unsafe.Pointer, target [NodeIDSize]byte, addr Address, fd uintptr) (unsafe.Pointer, int)

ClientConnectFd dials over a caller-owned udp socket, blocking (nwep_client_connect_fd).

func ClientConnectFdAsync

func ClientConnectFdAsync(identity unsafe.Pointer, target [NodeIDSize]byte, addr Address, fd uintptr) (unsafe.Pointer, int)

ClientConnectFdAsync starts a non-blocking connect over a caller socket (nwep_client_connect_fd_async).

func ClientConnectPoll

func ClientConnectPoll(client unsafe.Pointer) int

ClientConnectPoll advances an async connect, returning would-block until ready (nwep_client_connect_poll).

func ClientFd

func ClientFd(client unsafe.Pointer) uintptr

ClientFd returns the client's udp socket handle (nwep_client_fd).

func ClientIsAlive

func ClientIsAlive(client unsafe.Pointer) bool

ClientIsAlive reports whether the connection is still usable (nwep_client_is_alive).

func ClientNextTimeoutMs

func ClientNextTimeoutMs(client unsafe.Pointer, nowMs int64) int

ClientNextTimeoutMs returns ms until the next timer, or negative for none (nwep_client_next_timeout_ms).

func ClientOpenStream

func ClientOpenStream(client unsafe.Pointer, method int, path string, headers [][2]string) (uint64, int)

ClientOpenStream opens a streamed read, returning the stream id (nwep_client_open_stream).

func ClientPeerPubkey

func ClientPeerPubkey(client unsafe.Pointer) (pubkey [PubKeySize]byte, rc int)

ClientPeerPubkey copies out the verified ed25519 public key of the peer (nwep_client_peer_pubkey).

func ClientPollNotify

func ClientPollNotify(client unsafe.Pointer) unsafe.Pointer

ClientPollNotify returns the next buffered server NOTIFY, or nil (nwep_client_poll_notify).

func ClientRequestCancel

func ClientRequestCancel(client unsafe.Pointer, id uint64)

ClientRequestCancel abandons a submitted request by id (nwep_client_request_cancel).

func ClientRequestPoll

func ClientRequestPoll(client unsafe.Pointer, id uint64) (unsafe.Pointer, int)

ClientRequestPoll checks a submitted request, returning the response when ready (nwep_client_request_poll).

func ClientRequestSubmit

func ClientRequestSubmit(client unsafe.Pointer, method int, path string, headers [][2]string, body []byte) (uint64, int)

ClientRequestSubmit queues a non-blocking request, returning its id (nwep_client_request_submit).

func ClientSend

func ClientSend(client unsafe.Pointer, method int, path string, headers [][2]string, body []byte) (unsafe.Pointer, int)

ClientSend sends a request and blocks for the response (nwep_client_send).

func ClientSetCache

func ClientSetCache(client unsafe.Pointer, cache unsafe.Pointer) int

ClientSetCache attaches a response cache to the client, nil to detach (nwep_client_set_cache).

func ClientSetRequestDone

func ClientSetRequestDone(client unsafe.Pointer, fn RequestDoneFunc) int

ClientSetRequestDone registers the per-client request completion hook, nil to clear (nwep_client_set_request_done).

func ClientStreamClose

func ClientStreamClose(client unsafe.Pointer, streamID uint64)

ClientStreamClose releases a stream's client-side state (nwep_client_stream_close).

func ClientStreamRecv

func ClientStreamRecv(client unsafe.Pointer, streamID uint64, buf []byte) (n int, ended bool, rc int)

ClientStreamRecv reads the next chunk of a stream body into buf (nwep_client_stream_recv).

returns the bytes read, whether the stream ended (quic fin), and the c code.

func ClientStreamResponse

func ClientStreamResponse(client unsafe.Pointer, streamID uint64) (unsafe.Pointer, int)

ClientStreamResponse fetches the response headers of an opened stream (nwep_client_stream_response).

func ClientStreamVerify

func ClientStreamVerify(client unsafe.Pointer, streamID uint64, pubkey [PubKeySize]byte) int

ClientStreamVerify checks the running signature over a stream against pubkey (nwep_client_stream_verify).

func ClientTick

func ClientTick(client unsafe.Pointer, nowMs int64) int

ClientTick advances the client state machine at now_ms monotonic (nwep_client_tick).

func ClientVerifyResponse

func ClientVerifyResponse(client unsafe.Pointer, resp unsafe.Pointer, path string, nowSecs uint64) int

ClientVerifyResponse checks a response signature against the peer for path (nwep_client_verify_response).

func DhtAnnounce

func DhtAnnounce(dht unsafe.Pointer, serviceAddr Address, nowSecs uint64) int

DhtAnnounce publishes this node's service address to the dht (nwep_dht_announce).

func DhtAttach

func DhtAttach(server unsafe.Pointer, bootstrap []BootstrapEntry, initialSeq uint64) (unsafe.Pointer, int)

DhtAttach attaches a dht to a server, seeding it with bootstrap nodes (nwep_dht_attach).

func DhtBootstrap

func DhtBootstrap(dht unsafe.Pointer, nowSecs uint64) int

DhtBootstrap kicks off the initial self-lookup to populate routing (nwep_dht_bootstrap).

func DhtClose

func DhtClose(dht unsafe.Pointer)

DhtClose detaches and frees the dht (nwep_dht_close).

func DhtNextTimeoutMs

func DhtNextTimeoutMs(dht unsafe.Pointer, nowSecs uint64) int

DhtNextTimeoutMs returns ms until the next dht timer, or negative for none (nwep_dht_next_timeout_ms).

func DhtStartLookup

func DhtStartLookup(dht unsafe.Pointer, target [NodeIDSize]byte, nowSecs uint64) int

DhtStartLookup begins an iterative find_value for a node_id (nwep_dht_start_lookup).

func DhtTick

func DhtTick(dht unsafe.Pointer, nowSecs uint64) int

DhtTick advances the dht state machine at now_secs unix time (nwep_dht_tick).

func Ed25519Sign

func Ed25519Sign(msg []byte, privkey [PrivKeySize]byte) (sig [64]byte, rc int)

Ed25519Sign signs msg with a private key, returning the 64-byte signature (nwep_ed25519_sign).

func Ed25519Verify

func Ed25519Verify(sig [64]byte, msg []byte, pubkey [PubKeySize]byte) int

Ed25519Verify verifies a 64-byte signature over msg under pubkey (nwep_ed25519_verify).

func GenesisCheckpointCreate

func GenesisCheckpointCreate(blsSecrets, blsPubkeys, indices []byte, nFounders, threshold int) ([]byte, int)

GenesisCheckpointCreate builds the founding checkpoint for a fresh network (nwep_genesis_checkpoint_create).

blsSecrets is nFounders concatenated 32-byte secrets, blsPubkeys nFounders concatenated 48-byte keys, indices one byte per founder.

func IdentityGenerate

func IdentityGenerate() (nodeID [NodeIDSize]byte, keypair unsafe.Pointer, rc int)

IdentityGenerate generates a fresh ed25519 identity (nwep_identity_generate).

the keypair is allocated in c memory and returned as an opaque pointer so the private half never enters the go heap, free it with KeypairFree. returns the derived node_id, the keypair pointer, and the raw c return code.

func IsFatal

func IsFatal(code int) bool

IsFatal reports whether code kills the connection, not retryable (nwep_is_fatal).

func KeybindingCreate

func KeybindingCreate(pubkey [PubKeySize]byte, recoveryCommitment [32]byte, timestamp uint64, privkey [PrivKeySize]byte) ([]byte, int)

KeybindingCreate builds a signed key binding entry (nwep_keybinding_create).

func KeypairFree

func KeypairFree(keypair unsafe.Pointer)

KeypairFree zeroizes the private half then frees a keypair (from IdentityGenerate or KeypairLoadPem).

func KeypairLoadPem

func KeypairLoadPem(pem []byte) (keypair unsafe.Pointer, rc int)

KeypairLoadPem decodes pem bytes into a keypair (nwep_keypair_load_pem).

the keypair is allocated in c memory like IdentityGenerate, free it with KeypairFree. returns the keypair pointer and the c return code.

func KeypairPrivKey

func KeypairPrivKey(keypair unsafe.Pointer) [PrivKeySize]byte

KeypairPrivKey copies out the 32-byte private half (secret material, wipe after use).

this is the raw escape hatch, the safe layer keeps the private key in c memory and never calls this. zero the returned array when done.

func KeypairPubKey

func KeypairPubKey(keypair unsafe.Pointer) [PubKeySize]byte

KeypairPubKey copies out the 32-byte public half of a keypair (no secret material).

func KeypairSavePem

func KeypairSavePem(keypair unsafe.Pointer) ([]byte, int)

KeypairSavePem encodes a keypair as unencrypted pkcs8 pem (nwep_keypair_save_pem).

returns the pem bytes (secret material, wipe after use) and the c return code.

func KeyrotationCreate

func KeyrotationCreate(nodeID [NodeIDSize]byte, oldPubkey, newPubkey [PubKeySize]byte, timestamp, overlapExpiry uint64, oldPrivkey, newPrivkey [PrivKeySize]byte) ([]byte, int)

KeyrotationCreate builds a signed key rotation entry, signed by both keys (nwep_keyrotation_create).

func LogAppend

func LogAppend(log unsafe.Pointer, bytes []byte) int64

LogAppend appends an entry and returns its index, or a negative code (nwep_log_append).

func LogCreate

func LogCreate() unsafe.Pointer

LogCreate allocates an empty append-only merkle log (nwep_log_create).

func LogEntryType

func LogEntryType(bytes []byte) int

LogEntryType returns the entry-type tag of an encoded log entry (nwep_log_entry_type).

func LogFree

func LogFree(log unsafe.Pointer)

LogFree frees a log (nwep_log_free).

func LogRoot

func LogRoot(log unsafe.Pointer) (root [32]byte, rc int)

LogRoot copies out the current merkle root, rfc-6962 (nwep_log_root).

func LogServerCreate

func LogServerCreate(identity unsafe.Pointer, log unsafe.Pointer) unsafe.Pointer

LogServerCreate wraps a log behind a server that answers log queries (nwep_log_server_create).

func LogServerDispatch

func LogServerDispatch(ls unsafe.Pointer, connID uint64, req, buf unsafe.Pointer, nowSecs int64) int

LogServerDispatch answers a log request into buf, called from a handler (nwep_log_server_dispatch).

func LogServerFree

func LogServerFree(ls unsafe.Pointer)

LogServerFree frees a log server and retires its on-append hook (nwep_log_server_free).

func LogServerSetOnAppend

func LogServerSetOnAppend(ls unsafe.Pointer, fn LogAppendFunc)

LogServerSetOnAppend registers the accepted-entry persistence hook, nil to clear (nwep_log_server_set_on_append).

func LogSize

func LogSize(log unsafe.Pointer) uint64

LogSize returns the number of entries in the log (nwep_log_size).

func MessageFree

func MessageFree(msg unsafe.Pointer)

MessageFree frees a message handle owned by the caller (nwep_message_free).

func MessageGetBody

func MessageGetBody(msg unsafe.Pointer) []byte

MessageGetBody copies out the decoded body bytes (nwep_message_get_body).

func MessageGetHeader

func MessageGetHeader(msg unsafe.Pointer, name string) string

MessageGetHeader returns the value of header name, or empty when absent (nwep_message_get_header).

func MessageGetStatus

func MessageGetStatus(msg unsafe.Pointer) string

MessageGetStatus returns the response status string, or empty for a request (nwep_message_get_status).

func MessageHeaderAt

func MessageHeaderAt(msg unsafe.Pointer, i int) (name, value string, rc int)

MessageHeaderAt returns the name and value of header i (nwep_message_header_at).

func MessageHeaderCount

func MessageHeaderCount(msg unsafe.Pointer) int

MessageHeaderCount returns how many headers the message carries (nwep_message_header_count).

func MethodStr

func MethodStr(method int) string

MethodStr returns the human name of a method code (nwep_method_str).

func NodeidFromBase58

func NodeidFromBase58(text string) (nodeID [NodeIDSize]byte, rc int)

NodeidFromBase58 decodes a base58 string into a node_id (nwep_nodeid_from_base58).

func NodeidFromPubkey

func NodeidFromPubkey(pubkey [PubKeySize]byte) (nodeID [NodeIDSize]byte, rc int)

NodeidFromPubkey derives the node_id of an ed25519 public key (nwep_nodeid_from_pubkey).

func NodeidToBase58

func NodeidToBase58(nodeID [NodeIDSize]byte) (string, int)

NodeidToBase58 encodes a node_id as a base58 string (nwep_nodeid_to_base58).

func NodeidVerify

func NodeidVerify(nodeID [NodeIDSize]byte, pubkey [PubKeySize]byte) int

NodeidVerify checks node_id is sha-256(pubkey + "WEB/1"), constant time (nwep_nodeid_verify).

func RequestIsFresh

func RequestIsFresh(req unsafe.Pointer, etag string) int

RequestIsFresh reports whether a conditional request still matches etag (nwep_request_is_fresh).

returns 1 when the cached representation is fresh (a 304 may be sent), 0 when stale, or a negative code.

func ResponseBlit

func ResponseBlit(buf unsafe.Pointer, frame []byte) int

ResponseBlit writes a pre-encoded response frame straight into buf (nwep_response_blit).

func ResponseCapture

func ResponseCapture(buf unsafe.Pointer) ([]byte, int)

ResponseCapture copies the encoded response frame out of buf (nwep_response_capture).

returns the captured frame bytes, sized by a first probe call, and the code.

func ResponseHeader

func ResponseHeader(buf unsafe.Pointer, name, value string) int

ResponseHeader appends one header to a response being built in buf (nwep_response_header).

func ResponseNotModified

func ResponseNotModified(buf unsafe.Pointer, etag string) int

ResponseNotModified writes a 304 not-modified carrying etag into buf (nwep_response_not_modified).

func ResponseOk

func ResponseOk(buf unsafe.Pointer, body []byte) int

ResponseOk writes a 200 ok response with body into buf (nwep_response_ok).

func ResponsePartial

func ResponsePartial(buf unsafe.Pointer, body []byte, ranges []Range, contentType string) int

ResponsePartial writes a 206 partial response for the given ranges into buf (nwep_response_partial).

func ResponseRangeNotSatisfiable

func ResponseRangeNotSatisfiable(buf unsafe.Pointer, totalLen uint64) int

ResponseRangeNotSatisfiable writes a 416 with the resource length into buf (nwep_response_range_not_satisfiable).

func ResponseRelay

func ResponseRelay(buf unsafe.Pointer, origin unsafe.Pointer) int

ResponseRelay writes an upstream response back out verbatim into buf (nwep_response_relay).

func ResponseStatus

func ResponseStatus(buf unsafe.Pointer, status string, body []byte) int

ResponseStatus writes a response with an explicit status and body into buf (nwep_response_status).

func ResponseVerify

func ResponseVerify(resp unsafe.Pointer, pubkey [PubKeySize]byte, path string, nowSecs uint64) int

ResponseVerify checks a response signature against pubkey for path at now (nwep_response_verify).

func ReusePortSupported

func ReusePortSupported() bool

ReusePortSupported reports whether the platform supports SO_REUSEPORT (nwep_reuse_port_supported).

func RevocationCreate

func RevocationCreate(nodeID [NodeIDSize]byte, revokedPubkey, recoveryPubkey [PubKeySize]byte, reason uint8, timestamp uint64, recoveryPrivkey [PrivKeySize]byte) ([]byte, int)

RevocationCreate builds a signed revocation entry, signed by the recovery key (nwep_revocation_create).

func ServerBeginStream

func ServerBeginStream(server unsafe.Pointer, connID, streamID uint64, path, status string, headers [][2]string) int

ServerBeginStream opens a server-pushed streamed response (nwep_server_begin_stream).

func ServerClose

func ServerClose(server unsafe.Pointer)

ServerClose stops the server, frees it, and retires its handler (nwep_server_close).

func ServerConnCompression

func ServerConnCompression(server unsafe.Pointer, connID uint64) int

ServerConnCompression reports whether a connection negotiated body compression (nwep_server_conn_compression).

func ServerDrain

func ServerDrain(server unsafe.Pointer) int

ServerDrain begins a graceful drain, refusing new connections (nwep_server_drain).

func ServerFd

func ServerFd(server unsafe.Pointer) uintptr

ServerFd returns the udp socket handle to fold into a reactor (nwep_server_fd).

returned as uintptr to hold a posix int or a windows SOCKET NWG1200.

func ServerGetPeerNodeid

func ServerGetPeerNodeid(server unsafe.Pointer, connID uint64) (nodeID [NodeIDSize]byte, rc int)

ServerGetPeerNodeid returns the verified node_id of a connection's peer (nwep_server_get_peer_nodeid).

func ServerIsDrained

func ServerIsDrained(server unsafe.Pointer) bool

ServerIsDrained reports whether the drain has completed (nwep_server_is_drained).

func ServerLastHandshakeError

func ServerLastHandshakeError(server unsafe.Pointer) int

ServerLastHandshakeError returns the last handshake failure code, for diagnostics (nwep_server_last_handshake_error).

func ServerListen

func ServerListen(identity unsafe.Pointer, addr Address) (unsafe.Pointer, int)

ServerListen binds a udp socket and allocates a server (nwep_server_listen).

func ServerListenFd

func ServerListenFd(identity unsafe.Pointer, fd uintptr) (unsafe.Pointer, int)

ServerListenFd adopts a caller-owned udp socket (nwep_server_listen_fd).

func ServerListenFdSharded

func ServerListenFdSharded(identity unsafe.Pointer, fd uintptr, shardID uint16) (unsafe.Pointer, int)

ServerListenFdSharded adopts a socket as one shard of a reuseport set (nwep_server_listen_fd_sharded).

func ServerListenReuseport

func ServerListenReuseport(identity unsafe.Pointer, addr Address) (unsafe.Pointer, int)

ServerListenReuseport binds with SO_REUSEPORT for multi-socket sharding (nwep_server_listen_reuseport).

func ServerLoad

func ServerLoad(server unsafe.Pointer) int

ServerLoad returns the current load gauge, 0 to 100 (nwep_server_load).

func ServerLocalNodeid

func ServerLocalNodeid(server unsafe.Pointer) (nodeID [NodeIDSize]byte, rc int)

ServerLocalNodeid returns the server's own node_id (nwep_server_local_nodeid).

func ServerLocalPort

func ServerLocalPort(server unsafe.Pointer) uint16

ServerLocalPort returns the bound udp port (nwep_server_local_port).

func ServerNextTimeoutMs

func ServerNextTimeoutMs(server unsafe.Pointer, nowMs int64) int

ServerNextTimeoutMs returns ms until the next timer, or negative for none (nwep_server_next_timeout_ms).

func ServerNotify

func ServerNotify(server unsafe.Pointer, connID uint64, event string, headers [][2]string, body []byte) int

ServerNotify pushes a server-initiated NOTIFY on a connection (nwep_server_notify).

func ServerRelay

func ServerRelay(server unsafe.Pointer, connID, streamID uint64, originResp unsafe.Pointer) int

ServerRelay relays an upstream response back to a deferred request (nwep_server_relay).

func ServerRespond

func ServerRespond(server unsafe.Pointer, connID, streamID uint64, status string, body []byte) int

ServerRespond delivers a deferred response out of band after a handler deferred (nwep_server_respond).

func ServerRespondBlit

func ServerRespondBlit(server unsafe.Pointer, connID, streamID uint64, frame []byte) int

ServerRespondBlit delivers a pre-encoded frame as a deferred response (nwep_server_respond_blit).

func ServerRespondHeader

func ServerRespondHeader(server unsafe.Pointer, connID, streamID uint64, name, value string) int

ServerRespondHeader appends a header to an out-of-band deferred response (nwep_server_respond_header).

func ServerSetHandler

func ServerSetHandler(server unsafe.Pointer, fn HandlerFunc) int

ServerSetHandler registers the request handler, or clears it with a nil fn (nwep_server_set_handler).

func ServerSetMaxParked

func ServerSetMaxParked(server unsafe.Pointer, maxParked int)

ServerSetMaxParked caps the number of deferred responses outstanding (nwep_server_set_max_parked).

func ServerSetOverloaded

func ServerSetOverloaded(server unsafe.Pointer, on bool)

ServerSetOverloaded toggles the front-door shed switch (nwep_server_set_overloaded).

func ServerStreamEnd

func ServerStreamEnd(server unsafe.Pointer, connID, streamID uint64) int

ServerStreamEnd finishes a streamed response with a quic fin (nwep_server_stream_end).

func ServerStreamSend

func ServerStreamSend(server unsafe.Pointer, connID, streamID uint64, body []byte) int

ServerStreamSend sends a chunk of a streamed response body (nwep_server_stream_send).

func ServerTick

func ServerTick(server unsafe.Pointer, nowMs int64) int

ServerTick advances the server state machine at now_ms monotonic (nwep_server_tick).

func ShamirCombine

func ShamirCombine(shares []byte, nShares, shareLen int) ([]byte, int)

ShamirCombine recombines n_shares concatenated shares back into the secret (nwep_shamir_combine).

the secret is shareLen-1 bytes, so a shareLen buffer is always ample.

func ShamirSplit

func ShamirSplit(secret []byte, t, n int) ([]byte, int)

ShamirSplit splits secret into n shares, any t of which recombine it (nwep_shamir_split).

each share is 1 + len(secret) bytes (a 1-based index byte then data), so the output size is exact and needs no sizing probe. returns the concatenated share bytes and the c return code.

func StatusStr

func StatusStr(status int) string

StatusStr returns the human name of a status code (nwep_status_str).

func Strerror

func Strerror(code int) string

Strerror returns the human message for an nwep error code (nwep_strerror).

func TrustStoreApplyAnchorChange

func TrustStoreApplyAnchorChange(ts unsafe.Pointer, entryBytes []byte, currentEpoch uint64) int

TrustStoreApplyAnchorChange applies a signed anchor-set change at an epoch (nwep_trust_store_apply_anchor_change).

func TrustStoreCreate

func TrustStoreCreate() unsafe.Pointer

TrustStoreCreate allocates an empty trust store (nwep_trust_store_create).

func TrustStoreEvaluateKeyRotation

func TrustStoreEvaluateKeyRotation(rotationBytes []byte, presentedPubkey [32]byte, nowSecs int64) int

TrustStoreEvaluateKeyRotation checks whether a rotation justifies a presented key (nwep_trust_store_evaluate_key_rotation).

func TrustStoreFree

func TrustStoreFree(ts unsafe.Pointer)

TrustStoreFree frees a trust store (nwep_trust_store_free).

func TrustStoreLoad

func TrustStoreLoad(ts unsafe.Pointer, bytes []byte) int

TrustStoreLoad restores a store from saved bytes, re-verifying as it loads (nwep_trust_store_load).

func TrustStoreLoadGenesisAnchors

func TrustStoreLoadGenesisAnchors(ts unsafe.Pointer, pubkeys []byte, n int) int

TrustStoreLoadGenesisAnchors seeds the store with n concatenated 48-byte anchor keys (nwep_trust_store_load_genesis_anchors).

func TrustStoreMaxLogSize

func TrustStoreMaxLogSize(ts unsafe.Pointer) uint64

TrustStoreMaxLogSize returns the largest log size the store has seen (nwep_trust_store_max_log_size).

func TrustStoreObserveLogSize

func TrustStoreObserveLogSize(ts unsafe.Pointer, observed uint64) int

TrustStoreObserveLogSize records a seen log size to detect rollback (nwep_trust_store_observe_log_size).

func TrustStoreSave

func TrustStoreSave(ts unsafe.Pointer) ([]byte, int)

TrustStoreSave serializes the store for persistence (nwep_trust_store_save).

func TrustStoreUpdateCheckpoint

func TrustStoreUpdateCheckpoint(ts unsafe.Pointer, cpBytes []byte, nowSecs int64) int

TrustStoreUpdateCheckpoint verifies and adopts a newer checkpoint (nwep_trust_store_update_checkpoint).

func TrustStoreVerifyKey

func TrustStoreVerifyKey(ts, client unsafe.Pointer, nodeID, recoveryCommitment [32]byte, nowSecs int64) int

TrustStoreVerifyKey resolves and verifies a node's current key via a log client (nwep_trust_store_verify_key).

func TrustStoreVerifyKeyBinding

func TrustStoreVerifyKeyBinding(ts unsafe.Pointer, nodeID, expectedPubkey [32]byte, bundle []byte, nowSecs int64) int

TrustStoreVerifyKeyBinding verifies a key binding bundle offline against the store (nwep_trust_store_verify_key_binding).

func TrustVersion

func TrustVersion() string

TrustVersion returns the trust-layer version string (nwep_trust_version).

func URIParse

func URIParse(input string) (nodeID [NodeIDSize]byte, port uint16, path string, rc int)

URIParse parses a web://nodeid_base58[:port]/path uri (nwep_uri_parse).

returns the target node_id, the port (0 when absent), and the path. the c path borrows the input buffer, so it is copied out into an owned go string here.

func Version

func Version() string

Version returns the library version string, for example 0.1.0 (nwep_version).

func Zeroize

func Zeroize(ptr unsafe.Pointer, length int)

Zeroize wipes length bytes at ptr, for clearing secret material (nwep_zeroize).

safety

ptr must point at length valid writable bytes. used by the safe layer to wipe c-owned secrets before free, callers below it should not need this directly.

Types

type Address

type Address [32]byte

Address is the raw 32-byte opaque nwep_address storage, never inspected directly.

web/1 is ipv6 only, ipv4 callers embed a v4 address with AddressIPv4Mapped. the size matches the header's opaque[32], asserted in the tests.

func AddressFromBytes

func AddressFromBytes(addr [16]byte, port uint16) Address

AddressFromBytes returns the address for a raw 16-byte ipv6 address at port (nwep_address_from_bytes).

func AddressIPv4Mapped

func AddressIPv4Mapped(a, b, c, d byte, port uint16) Address

AddressIPv4Mapped returns the ::ffff:a.b.c.d ipv4-mapped form at port (nwep_address_ipv4_mapped).

func AddressLoopback

func AddressLoopback(port uint16) Address

AddressLoopback returns the ::1 loopback at port (nwep_address_loopback).

func AddressWildcard

func AddressWildcard(port uint16) Address

AddressWildcard returns the :: wildcard at port, for binding any interface (nwep_address_wildcard).

type BootstrapEntry

type BootstrapEntry struct {
	NodeID [NodeIDSize]byte
	Addr   Address
}

BootstrapEntry is a known node to seed the routing table, a node_id and address.

func DhtParseBootstrap

func DhtParseBootstrap(input string) (BootstrapEntry, int)

DhtParseBootstrap parses a "<nodeid>@[<ipv6>]:<port>" entry (nwep_dht_parse_bootstrap).

type CacheStats

type CacheStats struct {
	Hits, Misses, Stores, Evictions uint64
}

CacheStats is a snapshot of a cache's hit, miss, store, and eviction counters.

func CacheStatsGet

func CacheStatsGet(cache unsafe.Pointer) CacheStats

CacheStatsGet reads the cache's counters (nwep_cache_stats).

type ClientMetrics

type ClientMetrics struct {
	RequestsInflight  uint64
	RequestsCompleted uint64
	RequestsFailed    uint64
	SmoothedRTTus     uint64
	Alive             int32
}

ClientMetrics mirrors nwep_client_metrics, a pull-model snapshot of one connection.

func ClientMetricsGet

func ClientMetricsGet(client unsafe.Pointer) (ClientMetrics, int)

ClientMetricsGet fills a metrics snapshot from the client (nwep_client_metrics_get).

type DhtMetrics

type DhtMetrics struct {
	DatagramsSent     uint64
	DatagramsReceived uint64
	BytesSent         uint64
	BytesReceived     uint64
}

DhtMetrics mirrors nwep_dht_metrics, the dht's own datagram counters.

func DhtMetricsGet

func DhtMetricsGet(dht unsafe.Pointer) (DhtMetrics, int)

DhtMetricsGet fills a metrics snapshot from the dht (nwep_dht_metrics_get).

type DhtRecord

type DhtRecord struct {
	NodeID    [NodeIDSize]byte
	Addr      Address
	Pubkey    [PubKeySize]byte
	Seq       uint64
	Timestamp uint64
}

DhtRecord is a resolved announcement, what a lookup yields NW110300.

func DhtLookupResult

func DhtLookupResult(dht unsafe.Pointer, target [NodeIDSize]byte) (DhtRecord, int)

DhtLookupResult fetches a completed lookup's record, if resolved (nwep_dht_lookup_result).

type HandlerFunc

type HandlerFunc func(server unsafe.Pointer, connID, streamID uint64, req, buf unsafe.Pointer) int

HandlerFunc is the go form of nwep_handler_fn, run synchronously inside a tick.

it returns 0 for a synchronous answer (after writing buf), a negative code for a generic error response, or DeferSentinel to answer out of band later.

type KeyBinding

type KeyBinding struct {
	NodeID             [NodeIDSize]byte
	Pubkey             [PubKeySize]byte
	RecoveryCommitment [32]byte
	Timestamp          uint64
	Signature          [64]byte
}

KeyBinding mirrors nwep_keybinding, a node binding its pubkey and recovery commitment.

func KeybindingDecode

func KeybindingDecode(bytes []byte) (KeyBinding, int)

KeybindingDecode decodes a key binding entry (nwep_keybinding_decode).

type KeyRotation

type KeyRotation struct {
	NodeID        [NodeIDSize]byte
	OldPubkey     [PubKeySize]byte
	NewPubkey     [PubKeySize]byte
	Timestamp     uint64
	OverlapExpiry uint64
	SigOld        [64]byte
	SigNew        [64]byte
}

KeyRotation mirrors nwep_keyrotation, a signed handover from an old to a new key.

func KeyrotationDecode

func KeyrotationDecode(bytes []byte) (KeyRotation, int)

KeyrotationDecode decodes a key rotation entry (nwep_keyrotation_decode).

type LogAppendFunc

type LogAppendFunc func(entry []byte, index uint64)

LogAppendFunc is the go form of nwep_log_append_fn, the accepted-entry hook.

entry is copied into an owned slice before the call, so it stays valid.

type Range

type Range struct {
	Start, End uint64
}

Range is a byte range request, a half-open [Start, End) over a resource NW060800.

func RequestRange

func RequestRange(req unsafe.Pointer, totalLen uint64, etag string, maxOut int) ([]Range, int)

RequestRange parses the request range header against totalLen (nwep_request_range).

returns the satisfiable ranges (up to maxOut) and the c return code.

type RequestDoneFunc

type RequestDoneFunc func(client unsafe.Pointer, id uint64, status int, resp unsafe.Pointer)

RequestDoneFunc is the go form of nwep_request_done_fn, one per client.

on status 0 resp owns a message the callback must free with MessageFree, on a negative status resp is nil.

type Revocation

type Revocation struct {
	NodeID         [NodeIDSize]byte
	RevokedPubkey  [PubKeySize]byte
	RecoveryPubkey [PubKeySize]byte
	Reason         uint8
	Timestamp      uint64
	Signature      [64]byte
}

Revocation mirrors nwep_revocation, a signed retirement of a compromised key.

func RevocationDecode

func RevocationDecode(bytes []byte) (Revocation, int)

RevocationDecode decodes a revocation entry (nwep_revocation_decode).

type ServerMetrics

type ServerMetrics struct {
	ConnectionsActive   uint64
	ConnectionsAccepted uint64
	ConnectionsRefused  uint64
	ConnectionsClosed   uint64
	BytesReceived       uint64
	BytesSent           uint64
	DatagramsReceived   uint64
	DatagramsSent       uint64
	RequestsDispatched  uint64
	RequestsShed        uint64
	ParkedActive        uint64
	Load                int32
}

ServerMetrics mirrors nwep_server_metrics, a pull-model snapshot of counters.

func ServerMetricsGet

func ServerMetricsGet(server unsafe.Pointer) (ServerMetrics, int)

ServerMetricsGet fills a metrics snapshot from the server (nwep_server_metrics_get).

Jump to

Keyboard shortcuts

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