bee

package module
v1.2.1 Latest Latest
Warning

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

Go to latest
Published: May 8, 2026 License: MIT Imports: 15 Imported by: 0

README

bee-go

A Go client library for connecting to Swarm Bee nodes.

bee-go provides a type-safe interface for interacting with the Bee API. It targets functional parity with bee-js while keeping a Go shape: sub-packages per domain, context.Context first arg, errors as values, typed-bytes wrappers for length-validated identifiers.

Installation

go get github.com/ethswarm-tools/bee-go

Quickstart

package main

import (
	"context"
	"fmt"
	"log"
	"strings"

	bee "github.com/ethswarm-tools/bee-go"
	"github.com/ethswarm-tools/bee-go/pkg/swarm"
)

func main() {
	c, err := bee.NewClient("http://localhost:1633")
	if err != nil {
		log.Fatal(err)
	}

	ok, err := c.Debug.Health(context.Background())
	if err != nil || !ok {
		log.Fatal(err)
	}

	// Buy storage for 1 GB / 30 days using current chain pricing.
	size, _ := swarm.SizeFromGigabytes(1)
	batchID, err := c.BuyStorage(context.Background(), size, swarm.DurationFromDays(30), nil)
	if err != nil {
		log.Fatal(err)
	}

	res, err := c.File.UploadData(context.Background(), batchID, strings.NewReader("Hello Swarm!"), nil)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Uploaded reference: %s\n", res.Reference.Hex())
}

Package layout

bee-go is a sub-service client: the top-level Client exposes one sub-service per Bee API domain. This is a deliberate Go idiom — it keeps each domain's surface focused, allows compiler-checked imports of just what callers need, and avoids a single 100-method God object. (bee-js uses one flat Bee class because TypeScript has no equivalent of the import-pruning Go gives us for free.)

Package Purpose
pkg/swarm Typed bytes (Reference, BatchID, EthAddress, PublicKey, Signature, …), token math (BZZ, DAI), Duration, Size, BMT chunk ops, SOC creation, GSOC mining, typed errors (BeeError, BeeArgumentError, BeeResponseError), CheckResponse.
pkg/api Core HTTP client + shared options/headers. UploadOptions, RedundantUploadOptions, FileUploadOptions, CollectionUploadOptions, DownloadOptions, PostageBatchOptions. Pin/Tag/Stewardship/Grantee/Envelope endpoints.
pkg/file Data, file, chunk, SOC, feed and collection uploads/downloads. FeedReader/FeedWriter, MakeFeedIdentifier, FeedUpdateChunkReference, IsFeedRetrievable, AreAllSequentialFeedsUpdateRetrievable, in-memory UploadCollectionEntries.
pkg/postage Postage batch CRUD + stamp math (GetStampCost, GetStampDuration, GetAmountForDuration, GetDepthForSize, GetStampEffectiveBytes). Stamper for offline stamp generation.
pkg/debug Node info, peers, topology, balances, settlements, chequebook, stake, transactions, redistribution.
pkg/pss PSS send/subscribe/receive over WebSockets.
pkg/gsoc Generic Single-Owner Chunk send/subscribe (built on pkg/file SOC upload).
pkg/manifest Mantaray trie + v0.2 wire format (single-chunk).

Full API reference: pkg.go.dev/github.com/ethswarm-tools/bee-go.

Top-level Client (in client.go) wires every sub-service to the same HTTP client and base URL. High-level helpers that span multiple sub-services (e.g. BuyStorage, ExtendStorage, GetStorageCost) live on Client itself in storage.go.

bee-js → bee-go cheat sheet

bee-js method bee-go call
bee.uploadData(stamp, data, opts) client.File.UploadData(ctx, batchID, data, opts)
bee.uploadFile(stamp, data, name, opts) client.File.UploadFile(ctx, batchID, data, name, contentType, opts)
bee.uploadFiles(stamp, files, opts) client.File.UploadCollectionEntries(ctx, batchID, entries, opts)
bee.uploadFilesFromDirectory(stamp, dir, opts) client.File.UploadCollection(ctx, batchID, dir, opts)
bee.streamFiles(stamp, files, ...) client.File.StreamCollectionEntries(ctx, batchID, entries, opts) (chunks files locally, uploads chunk-by-chunk, saves manifest recursively)
bee.streamDirectory(stamp, dir, ...) client.File.StreamDirectory(ctx, batchID, dir, opts)
bee.hashDirectory(dir) file.HashDirectory(dir) (offline — no upload, returns the manifest reference) — entries variant file.HashCollectionEntries(entries)
bee.uploadChunk(stamp, data, opts) client.File.UploadChunk(ctx, batchID, data, opts)
bee.downloadData(ref, opts) client.File.DownloadData(ctx, ref, opts)
bee.probeData(ref) client.File.ProbeData(ctx, ref) (HEAD /bytes — Content-Length only)
bee.downloadFile(ref, path, opts) client.File.DownloadFile(ctx, ref, opts)
bee.downloadChunk(ref, opts) client.File.DownloadChunk(ctx, ref, opts)
bee.uploadSOC(stamp, owner, id, sig, data, opts) client.File.UploadSOC(ctx, batchID, owner, id, sig, data, opts)
bee.makeContentAddressedChunk(payload) swarm.MakeContentAddressedChunk(payload) (offline CAC)
bee.makeSingleOwnerChunk(addr, span, payload, id, signer) swarm.MakeSingleOwnerChunk(id, payload, signer) (offline SOC)
bee.calculateSingleOwnerChunkAddress(id, owner) swarm.CalculateSingleOwnerChunkAddress(id, owner)
bee.makeSOCReader(owner) / makeSOCWriter(signer) client.File.MakeSOCReader(owner) / client.File.MakeSOCWriter(signer)
bee.createFeedManifest(stamp, topic, owner) client.File.CreateFeedManifest(ctx, batchID, owner, topic)
bee.makeFeedReader(topic, owner) client.File.MakeFeedReader(owner, topic)
bee.makeFeedWriter(topic, signer) client.File.MakeFeedWriter(signer, topic)
bee.fetchLatestFeedUpdate(owner, topic) client.File.FetchLatestFeedUpdate(ctx, owner, topic)
bee.isReferenceRetrievable(ref) client.API.IsRetrievable(ctx, ref)
bee.isFeedRetrievable(owner, topic, idx) client.File.IsFeedRetrievable(ctx, owner, topic, &idx, opts)
bee.createPostageBatch(amount, depth, opts) client.Postage.CreatePostageBatch(ctx, amount, depth, label)
bee.topUpBatch(id, amount) client.Postage.TopUpBatch(ctx, batchID, amount)
bee.diluteBatch(id, depth) client.Postage.DiluteBatch(ctx, batchID, depth)
bee.getPostageBatch(id) / getAllPostageBatch() client.Postage.GetPostageBatch(ctx, batchID) / GetPostageBatches(ctx)
bee.getPostageBatchBuckets(id) client.Postage.GetPostageBatchBuckets(ctx, batchID)
bee.getGlobalPostageBatches() (and the deprecated getAllGlobalPostageBatch()) client.Postage.GetGlobalPostageBatches(ctx) (alias GetAllGlobalPostageBatch)
bee.buyStorage(size, duration, opts) client.BuyStorage(ctx, size, duration, opts)
bee.getStorageCost(size, duration) client.GetStorageCost(ctx, size, duration, opts)
bee.extendStorage(id, size, duration) client.ExtendStorage(ctx, batchID, size, duration, opts)
bee.extendStorageSize(id, size) client.ExtendStorageSize(ctx, batchID, size, opts)
bee.extendStorageDuration(id, duration) client.ExtendStorageDuration(ctx, batchID, duration, opts)
bee.getExtensionCost(id, size, duration) client.GetExtensionCost(ctx, batchID, size, duration, opts)
bee.getSizeExtensionCost(id, size) client.GetSizeExtensionCost(ctx, batchID, size, opts)
bee.getDurationExtensionCost(id, duration) client.GetDurationExtensionCost(ctx, batchID, duration, opts)
bee.calculateTopUpForBzz(depth, bzz) client.CalculateTopUpForBzz(ctx, depth, bzz, opts)
bee.pin(ref) / unpin(ref) client.API.Pin(ctx, ref) / Unpin(ctx, ref)
bee.getPin(ref) / getAllPins() client.API.GetPin(ctx, ref) / ListPins(ctx)
bee.createTag() / getTag(uid) / retrieveTag(uid) client.API.CreateTag(ctx) / GetTag(ctx, uid) (alias RetrieveTag)
bee.getAllTags(opts) / deleteTag(uid) / updateTag(uid, tag) client.API.ListTags(ctx, offset, limit) / DeleteTag(ctx, uid) / UpdateTag(ctx, uid, tag)
bee.createEnvelope(stamp, ref) client.API.PostEnvelope(ctx, batchID, ref)
bee.getGrantees(ref) / createGrantees(stamp, list) / patchGrantees(stamp, ref, hist, add, rev) client.API.GetGrantees(ctx, ref) / CreateGrantees(ctx, batchID, list) / PatchGrantees(ctx, batchID, ref, hist, add, rev)
bee.reuploadPinnedData(stamp, ref) client.API.Reupload(ctx, ref, batchID)
bee.pssSend(stamp, topic, target, data, recipient) client.PSS.PssSend(ctx, topic, target, data, recipient)
bee.pssSubscribe(topic, handler) client.PSS.PssSubscribe(ctx, topic) (returns Subscription{Messages, Errors})
bee.pssReceive(topic, timeoutMs) client.PSS.PssReceive(ctx, topic, timeout)
bee.gsocMine(overlay, id, prox) swarm.GSOCMine(target, identifier, proximity)
bee.gsocSend(stamp, signer, id, data) client.GSOC.Send(ctx, batchID, signer, id, data, opts)
bee.gsocSubscribe(addr, id, handler) client.GSOC.Subscribe(ctx, owner, id)
bee.isConnected() / checkConnection() client.Debug.IsConnected(ctx) / CheckConnection(ctx) (pings the base URL)
bee.getHealth() client.Debug.GetHealth(ctx) (structured) — Health(ctx) returns just a bool
bee.getReadiness() client.Debug.Readiness(ctx)
bee.getVersions() client.Debug.GetVersions(ctx)
bee.isSupportedExactVersion() / isSupportedApiVersion() client.Debug.IsSupportedExactVersion(ctx) / IsSupportedApiVersion(ctx)
bee.isGateway() client.Debug.IsGateway(ctx)
bee.getNodeInfo() client.Debug.NodeInfo(ctx)
bee.getStatus() client.Debug.Status(ctx)
bee.getNodeAddresses() client.Debug.Addresses(ctx)
bee.getTopology() client.Debug.Topology(ctx)
bee.getPeers() client.Debug.Peers(ctx)
bee.getChainState() client.Debug.ChainState(ctx)
bee.getReserveState() client.Debug.ReserveState(ctx)
bee.getRedistributionState() client.Debug.RedistributionState(ctx)
bee.getStake() / stake(amount) / depositStake(amount) client.Debug.GetStake(ctx) / Stake(ctx, amount) / DepositStake(ctx, amount)
bee.getWithdrawableStake() / withdrawSurplusStake() client.Debug.GetWithdrawableStake(ctx) / WithdrawSurplusStake(ctx)
bee.migrateStake() client.Debug.MigrateStake(ctx)
bee.getAllBalances() / getPeerBalance(peer) client.Debug.GetBalances(ctx) / GetPeerBalance(ctx, peer)
bee.getPastDueConsumptionBalances() / getPastDueConsumptionPeerBalance(peer) client.Debug.GetPastDueConsumptionBalances(ctx) / GetPastDueConsumptionPeerBalance(ctx, peer)
bee.getSettlements(peer) / getAllSettlements() client.Debug.PeerSettlement(ctx, peer) / Settlements(ctx)
bee.getWalletBalance() client.Debug.GetWallet(ctx) (returns BZZ + native balances + chequebook + chainID)
bee.withdrawBZZToExternalWallet(amount, addr) / withdrawDAIToExternalWallet(amount, addr) client.Debug.WithdrawBZZ(ctx, amount, addr) / WithdrawDAI(ctx, amount, addr) (also WithdrawBZZToExternalWallet / WithdrawDAIToExternalWallet aliases)
bee.getChequebookAddress() / getChequebookBalance() (Chequebook field on client.Debug.GetWallet) / client.Debug.GetChequebookBalance(ctx)
bee.depositBZZToChequebook(amount) / withdrawBZZFromChequebook(amount) client.Debug.DepositTokens(ctx, amount) / WithdrawTokens(ctx, amount) (also DepositBZZToChequebook / WithdrawBZZFromChequebook aliases)
bee.getLastCheques() / getLastChequesForPeer(peer) client.Debug.LastCheques(ctx) / GetLastChequesForPeer(ctx, peer)
bee.getLastCashoutAction(peer) / cashoutLastCheque(peer, gasPrice) client.Debug.GetLastCashoutAction(ctx, peer) / CashoutLastCheque(ctx, peer, gasPrice)
bee.getAllPendingTransactions() / getPendingTransaction(hash) client.Debug.GetAllPendingTransactions(ctx) / GetPendingTransaction(ctx, hash)
bee.rebroadcastPendingTransaction(hash) / cancelPendingTransaction(hash, gasPrice) client.Debug.RebroadcastPendingTransaction(ctx, hash) / CancelPendingTransaction(ctx, hash, gasPrice)
bee.rchash(depth, anchor1, anchor2) client.Debug.RCHash(ctx, depth, anchor1, anchor2)
bee.getWelcomeMessage() / setWelcomeMessage(msg) client.Debug.GetWelcomeMessage(ctx) / SetWelcomeMessage(ctx, msg)
bee.getLoggers() / getLoggersByExpression(exp) / setLoggerVerbosity(exp) client.Debug.GetLoggers(ctx) / GetLoggersByExpression(ctx, exp) / SetLoggerVerbosity(ctx, exp)

Construct a dev-mode client with bee.NewDevClient(url) — it returns the same surface, but most chain/payment endpoints will return a *BeeResponseError 404 against a bee dev node.

Bee-only extras (not in bee-js)

These hit Bee node endpoints that bee-js does not expose; useful for operators / diagnostic tooling.

Endpoint bee-go call
GET /accounting client.Debug.GetAccounting(ctx) — full per-peer accounting (balances, thresholds, surpluses, ghost balance)
GET /status/peers client.Debug.StatusPeers(ctx) — parallel status snapshot of every connected peer
GET /status/neighborhoods client.Debug.StatusNeighborhoods(ctx) — reserve size + proximity per neighborhood
POST /connect/{multi-address} client.Debug.ConnectPeer(ctx, multiaddr) — manual peer dial

pkg/postage also exposes MarshalStamp(batchID, index, timestamp, signature) and ConvertEnvelopeToMarshaledStamp(envelope) for callers that need the on-wire stamp byte layout (e.g. when stamping outside the standard upload path).

Errors

Every endpoint returns either nil or a *swarm.BeeError, *swarm.BeeArgumentError, or *swarm.BeeResponseError. Inspect with errors.As:

if rerr, ok := swarm.IsBeeResponseError(err); ok {
    fmt.Printf("Bee returned %d %s for %s %s\n",
        rerr.Status, rerr.StatusText, rerr.Method, rerr.URL)
    fmt.Printf("Body: %s\n", rerr.ResponseBody)
}

swarm.CheckResponse(resp) is a one-line helper used internally and available to callers who construct their own requests.

Examples

examples/ contains short runnable programs:

  • examples/basic-usage — health check + node info
  • examples/buy-batch — purchase a postage batch
  • examples/upload-picture — upload a file
  • examples/download-picture — download a file
  • examples/status — read chain/reserve/redistribution state

Contribute

Contributions are welcome — please open an issue first for anything substantial. Run go test ./... before submitting; the test suite is self-contained (no live Bee node required).

License

MIT

Documentation

Overview

Package bee is a Go client library for connecting to Swarm Bee nodes.

It targets functional parity with bee-js (the canonical TypeScript client) while keeping a Go shape: sub-packages per Bee API domain, context.Context as first arg, errors as values, typed-bytes wrappers (Reference, BatchID, EthAddress, …) for length-validated identifiers.

Quickstart

Connect to a local node, buy a postage batch, upload a few bytes:

import (
    "context"
    "log"
    "strings"

    bee "github.com/ethswarm-tools/bee-go"
    "github.com/ethswarm-tools/bee-go/pkg/swarm"
)

func run() {
    c, err := bee.NewClient("http://localhost:1633")
    if err != nil { log.Fatal(err) }

    ctx := context.Background()
    if ok, _ := c.Debug.Health(ctx); !ok {
        log.Fatal("bee node not healthy")
    }

    size, _ := swarm.SizeFromGigabytes(1)
    batchID, err := c.BuyStorage(ctx, size, swarm.DurationFromDays(30), nil)
    if err != nil { log.Fatal(err) }

    res, err := c.File.UploadData(ctx, batchID, strings.NewReader("Hello Swarm!"), nil)
    if err != nil { log.Fatal(err) }
    log.Printf("uploaded reference: %s", res.Reference.Hex())
}

Package layout

bee-go is a sub-service client: the top-level Client exposes one sub-service per Bee API domain. This is a deliberate Go idiom — it keeps each domain's surface focused, allows compiler-checked imports of just what callers need, and avoids a single 100-method God object. (bee-js uses one flat Bee class because TypeScript has no equivalent of the import-pruning Go gives us for free.)

  • pkg/swarm typed bytes, token math (BZZ, DAI), Duration, Size, BMT chunk addressing, SOC creation, GSOC mining, typed errors (BeeError, BeeArgumentError, BeeResponseError), CheckResponse.
  • pkg/api core HTTP client + shared options/headers; pin, tag, stewardship, grantee, envelope endpoints.
  • pkg/file data, file, chunk, SOC, feed and collection uploads/downloads; FeedReader/FeedWriter; offline HashDirectory.
  • pkg/postage postage batch CRUD + stamp math (GetStampCost, GetStampDuration, GetAmountForDuration, GetDepthForSize); offline Stamper.
  • pkg/debug node info, peers, topology, balances, settlements, chequebook, stake, transactions, redistribution.
  • pkg/pss PSS send/subscribe/receive over WebSockets.
  • pkg/gsoc Generic Single-Owner Chunk send/subscribe.
  • pkg/manifest Mantaray trie + v0.2 wire format.

Top-level helpers that span multiple sub-services — Client.BuyStorage, Client.ExtendStorage, Client.GetStorageCost and friends — live on Client itself.

Dev mode

Use NewDevClient when targeting a "bee dev" node. The returned DevClient has the same surface as Client but the chain-state, chequebook, settlement, postage purchase and stake endpoints will return a *swarm.BeeResponseError with status 404.

Bee version compatibility

This client targets Bee 2.7.2-rc1 / API version 8.0.0 (the values pinned in pkg/debug.SupportedBeeVersionExact and pkg/debug.SupportedAPIVersion). Use pkg/debug.Service.IsSupportedExactVersion for a strict match or pkg/debug.Service.IsSupportedAPIVersion for a major-version-compatible check at startup. Older / newer Bee instances usually work — unknown response fields are ignored — but new endpoints will return 404 and breaking wire-format changes will surface as JSON parse errors.

Authentication, timeouts, and proxies

Client's default *http.Client applies DefaultHTTPTimeout (60 s) to every request and inherits proxy settings from the standard HTTP_PROXY / HTTPS_PROXY environment variables. To install a Bearer-token preset, use WithToken:

c, _ := bee.NewClient("https://bee.example.com",
    bee.WithToken(os.Getenv("BEE_TOKEN")))

For full control over transport, timeout, or proxy, pass a configured http.Client via WithHTTPClient:

httpc := &http.Client{Transport: myTransport, Timeout: 30 * time.Second}
c, _ := bee.NewClient("https://bee.example.com", bee.WithHTTPClient(httpc))

Bee gates `/stamps`, `/chequebook`, `/stake`, `/transactions`, and the operator endpoints behind tokens in production deployments.

No automatic retries are performed. If you need transport-level retry, wrap the http.RoundTripper (e.g. with hashicorp/go-retryablehttp) before passing it to WithHTTPClient.

Concurrency

*Client and the sub-services it owns are safe for concurrent use from multiple goroutines. Construct one Client per Bee node URL and share it across your program — the underlying *http.Client manages its own connection pool. Sub-services hold pointers back to the same HTTP client, so per-Client tweaks (timeout, transport, auth) apply uniformly.

Cancellation

Every endpoint takes a context.Context as its first argument. Cancelling the context aborts the in-flight HTTP request. For uploads, chunks already accepted by the local Bee node may remain in the local reserve but the upload is not committed (no manifest reference is returned). pkg/file.Service.StreamDirectory and pkg/file.Service.StreamCollectionEntries upload chunk-by-chunk and can leave orphan chunks if cancelled mid-stream.

Streaming vs. buffered transfers

Downloads stream by default: pkg/file.Service.DownloadData and pkg/file.Service.DownloadFile return an io.ReadCloser backed by the live HTTP body. Drain it with io.Copy for large payloads; io.ReadAll buffers everything in memory and will OOM on multi-GB references.

Uploads accept an io.Reader and stream the body to Bee. The streaming chunk-by-chunk variants (pkg/file.Service.StreamDirectory and friends) bound peak memory at the BMT chunk size (4 KiB × 128 branches) regardless of file size; the tar-based pkg/file.Service.UploadCollection keeps the tar stream itself in memory.

Errors and retryability

Every endpoint returns either nil or a *swarm.BeeError, *swarm.BeeArgumentError, or *swarm.BeeResponseError. Inspect with errors.As, or use the helper pkg/swarm.IsBeeResponseError:

if rerr, ok := swarm.IsBeeResponseError(err); ok {
    log.Printf("bee returned %d %s for %s %s",
        rerr.Status, rerr.StatusText, rerr.Method, rerr.URL)
}

As a rule of thumb: 5xx responses and transport errors (DNS, connection refused, EOF) are retry candidates with backoff; 4xx responses are caller bugs (invalid batch ID, depth out of range, immutable-flag mismatch) and re-issuing the same request will fail the same way. POST /bytes uploads are idempotent for the same (data, batchID) tuple — Bee returns the same content reference.

Observability

bee-go emits one slog.Debug record per HTTP round-trip via the HTTPLogger (defaults to slog.Default grouped under "bee.http"). Records carry method / url / status / elapsed_ms attributes; transport errors emit slog.Error. Records are silent unless the program configures slog at debug level — point HTTPLogger at a custom handler to capture them, or wrap the http.RoundTripper passed to WithHTTPClient for richer instrumentation. Bee's own pkg/debug.Service.GetLoggers / pkg/debug.Service.SetLogger surface controls server-side verbosity at runtime.

Testing

Point NewClient at an net/http/httptest.Server to test code that calls bee-go without running a real Bee:

srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    w.Write([]byte(`{"status":"ok","version":"2.7.2","apiVersion":"8.0.0"}`))
}))
defer srv.Close()
c, _ := bee.NewClient(srv.URL)
healthy, _ := c.Debug.Health(context.Background())

Common pitfalls

  • A freshly-purchased postage batch is not usable for ~2-3 minutes on Sepolia (block time × N confirmations). Polling pkg/postage.PostageBatch.Usable before uploading avoids the 422 "stamp not usable" error.
  • Dilute is one-way: depth can only grow, never shrink. Plan size budgets accordingly.
  • pkg/swarm.ReferenceFromHex accepts both 32-byte (plain) and 64-byte (encrypted) references — passing an encrypted reference to a plain download will silently return garbage. Match the reference type to how it was uploaded.
  • Feed updates require the same (topic, signer) pair every time. A new signer creates a new feed, not an update.
  • On a `bee dev` node, all chain / chequebook / stake endpoints return 404 — see DevClient.

Go version

bee-go requires Go 1.25 or newer (see go.mod).

Examples

Runnable programs live under examples/ in the source tree: basic-usage (health + node info), buy-batch (postage purchase), upload-picture / download-picture (file round-trip), status (chain/reserve/redistribution state), integration-check (live-Bee soak). See the README for a bee-js → bee-go cheat sheet.

Index

Examples

Constants

View Source
const DefaultHTTPTimeout = 60 * time.Second

DefaultHTTPTimeout is the request-level timeout applied to the *http.Client constructed by NewClient when no WithHTTPClient override is supplied. Go's net/http stock default is *no* timeout, which can leave a stuck connection hanging forever — bee-py / bee-rs both ship a sensible bound. Users who pass their own *http.Client via WithHTTPClient are responsible for setting their own timeout.

Variables

View Source
var HTTPLogger = slog.Default().WithGroup("bee.http")

HTTPLogger is the *slog.Logger used by the request-logging http.RoundTripper that the default client installs (see NewClient). It defaults to slog.Default with a "bee.http" group, so logs are silent unless the program configures a slog handler at debug level.

To redirect bee-go HTTP logs to a custom logger:

bee.HTTPLogger = slog.New(myHandler).WithGroup("bee.http")

Mirrors the bee-py "bee.http" logger.

Functions

This section is empty.

Types

type Client

type Client struct {

	// API is the cross-cutting endpoint group: pin, tag, stewardship,
	// grantee, envelope, and "is reference retrievable?" checks.
	API *api.Service
	// Debug is the operator / observability surface: health, versions,
	// peers, accounting, chequebook, stake, transactions, loggers.
	Debug *debug.Service
	// File handles every "data goes in or out of Bee" endpoint: bytes,
	// files, chunks, SOCs, feeds, and tar-packed collections.
	File *file.Service
	// Postage handles postage-batch CRUD; pure stamp math is exposed as
	// free functions in [pkg/postage].
	Postage *postage.Service
	// Swarm groups the offline helpers that don't need a Bee node
	// (e.g. content-addressed chunk construction).
	Swarm *swarm.Service
	// PSS is Postal Service: send / subscribe / receive over the
	// neighborhood-routed PSS layer.
	PSS *pss.Service
	// GSOC is Generic Single-Owner Chunk send / subscribe (built on top
	// of the SOC primitive in [pkg/swarm]).
	GSOC *gsoc.Service
	// contains filtered or unexported fields
}

Client is the top-level Bee API client. It bundles one sub-service per Bee API domain (see the package doc for the layout); construct it once with NewClient and reuse — every sub-service shares the same underlying *http.Client.

High-level helpers that span multiple sub-services (Client.BuyStorage, Client.ExtendStorage, Client.GetStorageCost and friends) live on Client itself.

Example (DownloadData)

Round-trip a payload through Bee: upload bytes then download them back by reference.

package main

import (
	"context"
	"fmt"
	"io"
	"log"

	bee "github.com/ethswarm-tools/bee-go"
	"github.com/ethswarm-tools/bee-go/pkg/swarm"
)

func main() {
	c, err := bee.NewClient("http://localhost:1633")
	if err != nil {
		log.Fatal(err)
	}

	ref, err := swarm.ReferenceFromHex("0000000000000000000000000000000000000000000000000000000000000000")
	if err != nil {
		log.Fatal(err)
	}

	body, err := c.File.DownloadData(context.Background(), ref, nil)
	if err != nil {
		log.Fatal(err)
	}

	data, err := io.ReadAll(body)
	_ = body.Close()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("downloaded %d bytes\n", len(data))
}
Example (Errors)

Translate a non-2xx error from Bee into something printable. Every endpoint returns either nil or a *swarm.BeeError / *swarm.BeeArgumentError / *swarm.BeeResponseError; use errors.As to inspect the Bee-side context.

package main

import (
	"context"
	"errors"
	"fmt"
	"log"

	bee "github.com/ethswarm-tools/bee-go"
	"github.com/ethswarm-tools/bee-go/pkg/swarm"
)

func main() {
	c, err := bee.NewClient("http://localhost:1633")
	if err != nil {
		log.Fatal(err)
	}

	_, err = c.Postage.GetPostageBatches(context.Background())
	if err == nil {
		return
	}

	var rerr *swarm.BeeResponseError
	if errors.As(err, &rerr) {
		fmt.Printf("bee returned %d %s for %s %s\n",
			rerr.Status, rerr.StatusText, rerr.Method, rerr.URL)
		return
	}
	fmt.Println("other error:", err)
}
Example (UploadData)

Upload a few bytes against an existing postage batch and print the returned reference.

package main

import (
	"context"
	"fmt"
	"log"
	"strings"

	bee "github.com/ethswarm-tools/bee-go"
	"github.com/ethswarm-tools/bee-go/pkg/swarm"
)

func main() {
	c, err := bee.NewClient("http://localhost:1633")
	if err != nil {
		log.Fatal(err)
	}

	batchID, err := swarm.BatchIDFromHex("0000000000000000000000000000000000000000000000000000000000000000")
	if err != nil {
		log.Fatal(err)
	}

	res, err := c.File.UploadData(context.Background(), batchID, strings.NewReader("Hello Swarm!"), nil)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("reference:", res.Reference.Hex())
}

func NewClient

func NewClient(rawURL string, opts ...ClientOption) (*Client, error)

NewClient constructs a Client pointing at a Bee node's REST API. The url should be the base address (e.g. "http://localhost:1633"); a trailing slash is appended if missing so relative paths resolve correctly. Sub-services are wired up in order so the returned Client is ready to use.

Returns an error only if rawURL fails to parse.

The default *http.Client uses DefaultHTTPTimeout; supply WithHTTPClient to override.

Example

Construct a Client against a local Bee node and check that the node is healthy.

package main

import (
	"context"
	"fmt"
	"log"
	"time"

	bee "github.com/ethswarm-tools/bee-go"
)

func main() {
	c, err := bee.NewClient("http://localhost:1633")
	if err != nil {
		log.Fatal(err)
	}

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	healthy, err := c.Debug.Health(ctx)
	cancel()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("healthy:", healthy)
}

func (*Client) BuyStorage

func (c *Client) BuyStorage(ctx context.Context, size swarm.Size, duration swarm.Duration, opts *StorageOptions) (swarm.BatchID, error)

BuyStorage creates a postage batch sized + funded for the given size and duration. Equivalent to bee-js Bee.buyStorage: compute depth from size, amount from duration + chainstate price, then CreatePostageBatch.

Example

Buy a postage batch sized for 1 GB and lasting 30 days using current chain pricing. The returned BatchID is what every upload method expects as its stamp argument.

package main

import (
	"context"
	"fmt"
	"log"

	bee "github.com/ethswarm-tools/bee-go"
	"github.com/ethswarm-tools/bee-go/pkg/swarm"
)

func main() {
	c, err := bee.NewClient("http://localhost:1633")
	if err != nil {
		log.Fatal(err)
	}

	size, err := swarm.SizeFromGigabytes(1)
	if err != nil {
		log.Fatal(err)
	}

	batchID, err := c.BuyStorage(context.Background(), size, swarm.DurationFromDays(30), nil)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("batch:", batchID.Hex())
}

func (*Client) CalculateTopUpForBzz

func (c *Client) CalculateTopUpForBzz(ctx context.Context, depth uint8, bzz swarm.BZZ, opts *StorageOptions) (*big.Int, swarm.Duration, error)

CalculateTopUpForBzz translates a BZZ budget into the amount-per-chunk to pass to TopUpBatch and the expected TTL extension that results. Mirrors bee-js Bee.calculateTopUpForBzz.

func (*Client) ExtendStorage

func (c *Client) ExtendStorage(ctx context.Context, batchID swarm.BatchID, size swarm.Size, duration swarm.Duration, opts *StorageOptions) error

ExtendStorage extends a batch's size (absolute) and duration (relative). Tops up to fund the new amount and dilutes if the new depth is greater. Mirrors bee-js Bee.extendStorage.

func (*Client) ExtendStorageDuration

func (c *Client) ExtendStorageDuration(ctx context.Context, batchID swarm.BatchID, duration swarm.Duration, opts *StorageOptions) error

ExtendStorageDuration tops up the batch by enough to extend its TTL by `duration`. Mirrors bee-js Bee.extendStorageDuration.

func (*Client) ExtendStorageSize

func (c *Client) ExtendStorageSize(ctx context.Context, batchID swarm.BatchID, size swarm.Size, opts *StorageOptions) error

ExtendStorageSize extends a batch's depth to cover `size`. Errors if the new depth is not strictly greater than the current depth.

func (*Client) GetDurationExtensionCost

func (c *Client) GetDurationExtensionCost(ctx context.Context, batchID swarm.BatchID, duration swarm.Duration, opts *StorageOptions) (swarm.BZZ, error)

GetDurationExtensionCost returns the BZZ cost of extending the batch's TTL by `duration`.

func (*Client) GetExtensionCost

func (c *Client) GetExtensionCost(ctx context.Context, batchID swarm.BatchID, size swarm.Size, duration swarm.Duration, opts *StorageOptions) (swarm.BZZ, error)

GetExtensionCost returns the cost of extending the batch by both size and duration. Mirrors bee-js Bee.getExtensionCost.

func (*Client) GetSizeExtensionCost

func (c *Client) GetSizeExtensionCost(ctx context.Context, batchID swarm.BatchID, size swarm.Size, opts *StorageOptions) (swarm.BZZ, error)

GetSizeExtensionCost returns the BZZ cost of extending the batch's depth (absolute) to cover `size`. Errors if the requested depth is not greater than the current depth.

func (*Client) GetStorageCost

func (c *Client) GetStorageCost(ctx context.Context, size swarm.Size, duration swarm.Duration, opts *StorageOptions) (swarm.BZZ, error)

GetStorageCost returns the BZZ cost of buying a batch sized for `size` and lasting `duration`. Mirrors bee-js Bee.getStorageCost.

func (*Client) Ping added in v1.2.0

func (c *Client) Ping(ctx context.Context) (time.Duration, error)

Ping issues GET /health and returns the round-trip duration. Useful for connection-status indicators in dashboards / TUIs. Mirrors bee-rs Client::ping and bee-py AsyncBee.ping.

type ClientOption

type ClientOption func(*Client)

ClientOption configures a Client at construction time. Pass any number to NewClient; options are applied in order before the sub-services are wired up, so options that swap out the *http.Client or websocket dialer take effect for every sub-service.

func WithHTTPClient

func WithHTTPClient(c *http.Client) ClientOption

WithHTTPClient overrides the *http.Client used for every sub-service. Useful for sharing a connection pool with surrounding code, setting a custom timeout, or installing a transport-level interceptor (auth, retries, instrumentation). The default is http.DefaultClient.

func WithToken added in v1.2.0

func WithToken(token string) ClientOption

WithToken installs a Bearer-token preset on every request issued by the Client to the configured Bee host. Equivalent to building an *http.Client whose Transport adds Authorization: Bearer <token> and passing it via WithHTTPClient. Mirrors bee-py AsyncBee.with_token / bee-rs Client::with_token.

The token is only attached when the request URL's host matches the host of the Client's base URL. This protects against credential leaks when a (compromised or misconfigured) Bee responds with a 3xx redirect to a third-party host: every redirect hop goes back through this RoundTripper, so a host check is the only thing that stops the token from following the redirect chain.

Cannot be combined with WithHTTPClient; the last option wins.

type DevClient

type DevClient struct {
	*Client
}

DevClient is a Bee client variant that talks to a Bee node running in "dev" mode (`bee dev`). It wraps the regular Client but documents the reduced surface — most chain-state, chequebook, settlement, postage purchase and stake endpoints are not available on dev nodes and will return a *BeeResponseError with status 404 if called.

Endpoints that work

  • Addresses / Topology / NodeInfo / Status (with dev-shaped, simpler JSON — the existing parsers tolerate the missing fields)
  • Health, Readiness
  • File upload/download (/bytes, /bzz, /chunks, /soc, /feeds)
  • PSS subscribe/send
  • GSOC subscribe/send
  • Tags, Pins, Stewardship, Grantees, Envelopes
  • The /stamps endpoints behave as no-ops in dev mode but do not 404

Endpoints that return 404

  • All chequebook endpoints — balance, deposit, withdraw, cheques, cashout (Service.GetChequebookBalance, .DepositTokens, .WithdrawTokens, .LastCheques, .GetLastChequesForPeer, .GetLastCashoutAction, .CashoutLastCheque).
  • All settlement endpoints — .Settlements, .PeerSettlement.
  • All stake endpoints — .GetStake, .Stake, .DepositStake, .WithdrawSurplusStake, .MigrateStake, .GetWithdrawableStake.
  • Pending-transaction lifecycle — .GetAllPendingTransactions, .GetPendingTransaction, .RebroadcastPendingTransaction, .CancelPendingTransaction.
  • Chain-state reads — .ChainState, .ReserveState, .RedistributionState.
  • The redistribution / RC-hash endpoint .RCHash.
  • The /accounting and /balances endpoints (per-peer accounting does not exist on a single-node dev instance).
  • High-level helpers that internally call any of the above — Client.BuyStorage, .GetStorageCost, .ExtendStorage*, etc.

Mirrors bee-js BeeDev. There is no separate Go type because the wire shape is a strict subset; using DevClient is purely a signal to the reader (and to future helpers that may want to short-circuit chain calls).

func NewDevClient

func NewDevClient(rawURL string, opts ...ClientOption) (*DevClient, error)

NewDevClient is the dev-mode equivalent of NewClient. Use against a `bee dev` node.

type Network

type Network int

Network identifies the chain the Bee node runs on. Used to pick the block time when computing TTL math (Gnosis = 5s, Ethereum mainnet = 12s historically — bee-js defaults non-gnosis to 15s, which we mirror).

const (
	// NetworkGnosis is the Gnosis chain (5-second blocks). The default
	// for production Bee deployments today.
	NetworkGnosis Network = iota
	// NetworkMainnet is Ethereum mainnet (15-second blocks per bee-js).
	NetworkMainnet
)

func (Network) BlockTimeSeconds

func (n Network) BlockTimeSeconds() uint64

BlockTimeSeconds returns the per-block time used for stamp TTL math.

type StorageOptions

type StorageOptions struct {
	Network         Network
	PostageOptions  *api.PostageBatchOptions
	Encryption      bool
	RedundancyLevel api.RedundancyLevel
}

StorageOptions configures BuyStorage / ExtendStorage. Encryption and RedundancyLevel slots are placeholders for future capacity-table lookups; today they are accepted but unused. Network selects block time for amount-from-duration math.

Mirrors bee-js's encryption / erasureCodeLevel / network fan-out across the storage methods.

Directories

Path Synopsis
examples
act-share command
Upload a file under an Access Control Trie (ACT), manage the grantee list (create / get / patch), and download as the publisher using the resulting history root.
Upload a file under an Access Control Trie (ACT), manage the grantee list (create / get / patch), and download as the publisher using the resulting history root.
basic-usage command
buy-batch command
chain-state command
Print the chain state Bee currently sees.
Print the chain state Bee currently sees.
encrypted-folder-walk command
encrypted-folder-walk uploads a small set of files as a collection, then downloads the manifest's root chunk and walks the fork tree recursively, fetching each child chunk and stitching the file paths back together.
encrypted-folder-walk uploads a small set of files as a collection, then downloads the manifest's root chunk and walks the fork tree recursively, fetching each child chunk and stitching the file paths back together.
encrypted-upload command
Upload bytes with encrypt=true, observe the 64-byte reference (32 bytes content address + 32 bytes encryption key), and round-trip the data.
Upload bytes with encrypt=true, observe the 64-byte reference (32 bytes content address + 32 bytes encryption key), and round-trip the data.
feed-history command
Write three feed updates, then walk indexes 0..N and print the timeline.
Write three feed updates, then walk indexes 0..N and print the timeline.
feed-manifest command
Create a feed manifest, then publish a couple of feed updates pointing at different content.
Create a feed manifest, then publish a couple of feed updates pointing at different content.
feed-update command
Sign and publish a Swarm feed update, then read it back.
Sign and publish a Swarm feed update, then read it back.
gsoc-mined-pubsub command
Demonstrate Generic SOC pub/sub:
Demonstrate Generic SOC pub/sub:
integration-check command
integration-check exercises bee-go against a real Bee node.
integration-check exercises bee-go against a real Bee node.
key-gen command
Generate a fresh secp256k1 keypair and print all the useful forms (private hex, compressed public hex, EIP-55 address).
Generate a fresh secp256k1 keypair and print all the useful forms (private hex, compressed public hex, EIP-55 address).
list-batches command
List every postage batch owned by this Bee node.
List every postage batch owned by this Bee node.
manifest-add-file command
Build a Mantaray manifest from a list of entries, hash it offline, then add a new entry, hash again, and upload via UploadCollectionEntries.
Build a Mantaray manifest from a list of entries, hash it offline, then add a new entry, hash again, and upload via UploadCollectionEntries.
manifest-move-file command
Move a file's path within a manifest by removing the fork at the old path and adding it at the new path, preserving the file's content reference.
Move a file's path within a manifest by removing the fork at the old path and adding it at the new path, preserving the file's content reference.
pinning-workflow command
Full pin lifecycle: upload → pin → list → is_retrievable → reupload → unpin → re-pin.
Full pin lifecycle: upload → pin → list → is_retrievable → reupload → unpin → re-pin.
pss-send-receive command
Listen for PSS messages on a topic, or send one.
Listen for PSS messages on a topic, or send one.
redundant-upload command
Upload data with erasure-coded redundancy.
Upload data with erasure-coded redundancy.
ref-to-cid command
Convert a Swarm reference to a CID and back.
Convert a Swarm reference to a CID and back.
soc-write-read command
Sign and upload three Single Owner Chunks at distinct identifiers, then read them back via the SOC reader.
Sign and upload three Single Owner Chunks at distinct identifiers, then read them back via the SOC reader.
stamp-cost command
Pure offline calculator: given a size, duration, per-chunk-per-block price, and a network, print the postage stamp depth and the total BZZ cost.
Pure offline calculator: given a size, duration, per-chunk-per-block price, and a network, print the postage stamp depth and the total BZZ cost.
stamp-cost-live command
Preview the BZZ cost of buying a batch using the live /chainstate price.
Preview the BZZ cost of buying a batch using the live /chainstate price.
stamp-utilization command
Per-bucket fill analysis for one batch.
Per-bucket fill analysis for one batch.
stamper-client-side command
Produce postage stamps offline using a client-side Stamper.
Produce postage stamps offline using a client-side Stamper.
status command
swarm-blog command
swarm-blog is a markdown-driven blog with a single stable URL.
swarm-blog is a markdown-driven blog with a single stable URL.
swarm-chat command
swarm-chat is a terminal chat over PSS.
swarm-chat is a terminal chat over PSS.
swarm-cost-monitor command
swarm-cost-monitor is an operator dashboard: batch TTLs counting down, current chain price, projected refill cost.
swarm-cost-monitor is an operator dashboard: batch TTLs counting down, current chain price, projected refill cost.
swarm-deploy command
swarm-deploy is a `git push`-style site deploy tool on Swarm.
swarm-deploy is a `git push`-style site deploy tool on Swarm.
swarm-feed-rss command
swarm-feed-rss is a read-only aggregator over N Swarm feeds.
swarm-feed-rss is a read-only aggregator over N Swarm feeds.
swarm-fs command
swarm-fs is filesystem-style staging for a Mantaray collection.
swarm-fs is filesystem-style staging for a Mantaray collection.
swarm-keyring command
swarm-keyring is a passphrase-encrypted secp256k1 key store.
swarm-keyring is a passphrase-encrypted secp256k1 key store.
swarm-paste command
swarm-paste pipes stdin into a Bee node and prints a sharable /bzz/<ref> URL.
swarm-paste pipes stdin into a Bee node and prints a sharable /bzz/<ref> URL.
swarm-pinner command
swarm-pinner watches a directory, uploads+pins new files, and periodically checks that pinned content is still retrievable.
swarm-pinner watches a directory, uploads+pins new files, and periodically checks that pinned content is still retrievable.
swarm-relay command
swarm-relay is a single-batch upload gateway with persisted bucket tracking.
swarm-relay is a single-batch upload gateway with persisted bucket tracking.
swarm-share command
swarm-share is revocable file sharing on Swarm.
swarm-share is revocable file sharing on Swarm.
swarm-vault command
swarm-vault is a personal encrypted file dropbox.
swarm-vault is a personal encrypted file dropbox.
tag-upload-progress command
Track an upload's network-sync progress with a Swarm tag.
Track an upload's network-sync progress with a Swarm tag.
upload-directory command
Recursively upload a folder as a Swarm website.
Recursively upload a folder as a Swarm website.
upload-picture command
pkg
api
Package api covers the core HTTP service used by every other bee-go sub-package, plus the cross-cutting endpoints that don't fit neatly into a single domain: pin, tag, stewardship, grantee, envelope, and "is reference retrievable?" checks.
Package api covers the core HTTP service used by every other bee-go sub-package, plus the cross-cutting endpoints that don't fit neatly into a single domain: pin, tag, stewardship, grantee, envelope, and "is reference retrievable?" checks.
debug
Package debug exposes the operator / observability endpoints of a Bee node: health and readiness, version + API-version checks, addresses / topology / peers, node info and status (full + per-peer + per-neighborhood), chain / reserve / redistribution state, balances and accounting, settlements, chequebook (balance + cheques + cashout), stake (deposit / withdraw / migrate), pending transactions, welcome message, and runtime loggers.
Package debug exposes the operator / observability endpoints of a Bee node: health and readiness, version + API-version checks, addresses / topology / peers, node info and status (full + per-peer + per-neighborhood), chain / reserve / redistribution state, balances and accounting, settlements, chequebook (balance + cheques + cashout), stake (deposit / withdraw / migrate), pending transactions, welcome message, and runtime loggers.
file
Package file implements every "data goes in or out of Bee" endpoint: raw bytes (/bytes), files (/bzz), chunks (/chunks), single-owner chunks (/soc), feeds (/feeds), and tar-packed collections (/bzz on a directory).
Package file implements every "data goes in or out of Bee" endpoint: raw bytes (/bytes), files (/bzz), chunks (/chunks), single-owner chunks (/soc), feeds (/feeds), and tar-packed collections (/bzz on a directory).
gsoc
Package gsoc implements Swarm Generic Single-Owner Chunk messaging.
Package gsoc implements Swarm Generic Single-Owner Chunk messaging.
manifest
Package manifest implements Mantaray, the patricia-trie file manifest used by Swarm.
Package manifest implements Mantaray, the patricia-trie file manifest used by Swarm.
postage
Package postage covers the Swarm postage-batch lifecycle plus the pure stamp math used to translate (size, duration) into (depth, amount) and back.
Package postage covers the Swarm postage-batch lifecycle plus the pure stamp math used to translate (size, duration) into (depth, amount) and back.
pss
Package pss implements Swarm Postal Service, the trustless publish/subscribe layer that piggy-backs on the chunk-routing topology of a Bee swarm.
Package pss implements Swarm Postal Service, the trustless publish/subscribe layer that piggy-backs on the chunk-routing topology of a Bee swarm.
swarm
Package swarm holds the foundational types every other bee-go sub-package depends on: typed length-validated byte arrays, token and time math, content-addressed chunk primitives, and the typed error hierarchy returned by every endpoint.
Package swarm holds the foundational types every other bee-go sub-package depends on: typed length-validated byte arrays, token and time math, content-addressed chunk primitives, and the typed error hierarchy returned by every endpoint.

Jump to

Keyboard shortcuts

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