thread

package
v0.24.1 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: Apache-2.0 Imports: 6 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package thread is the module's codec for the Thread operational dataset and the MeshCoP TLV stream it is written in (Thread spec §8.10), and the data model of a Thread node's diagnostics: the dataset a controller hands a Thread device in AddOrUpdateThreadNetwork, and the dataset a Thread Border Router serves and is given (ADR 0027).

Two readings of a dataset live here, each after its reference:

  • DecodeDataset and OperationalDataset are a semantic port of matter.js packages/protocol/src/thread/ at 862ad75f — WalkTLVs and EncodeTLVs are BasicTlvCodec.ts, TLVType is meshcopTlvTypes.ts, SecurityPolicy is SecurityPolicy.ts, OperationalDataset is OperationalDataset.ts, and the sentinel errors are errors.ts and the ThreadTlvError of BasicTlvCodec.ts. A dataset from DecodeDataset re-encodes byte-identically while no field moved, including the non-canonical forms real Border Routers emit (the one-byte CHANNEL, vendor orderings); a changed field is written in its canonical form, a dataset built in memory canonically throughout. The commissioner reads datasets this way.
  • DatasetView is connectedhomeip's OperationalDatasetView (src/lib/support/ThreadOperationalDataset.cpp at 6170af84): the first sub-TLV of each type, held to chip's sizes. The cluster servers that judge a dataset by chip's rules read it this way (cluster/netinfra, cluster/threadbr).

NodeDiagnostics and the types it carries are the diagnostics of a Thread node after matter.js packages/thread-br-client/src/diagnostic/ DiagnosticResponse.ts and tlv/diag/ at 862ad75f: what a border-router adapter (thread/otbr) reads and the ThreadNetworkDiagnostics server serves.

The package sits in the foundation layer (script/archcheck): standard library only, no state.

Index

Constants

View Source
const (
	// MaxDatasetLen is kSizeOperationalDataset, the largest operational
	// dataset (:36).
	MaxDatasetLen = 254
	// MaxNetworkNameLen is kSizeNetworkName (:38).
	MaxNetworkNameLen = 16
	// ExtPANIDLen is kSizeExtendedPanId (:39).
	ExtPANIDLen = 8
	// NetworkKeyLen is kSizeMasterKey (:40).
	NetworkKeyLen = 16
	// MeshLocalPrefixLen is kSizeMeshLocalPrefix (:41).
	MeshLocalPrefixLen = 8
	// PSKcLen is kSizePSKc (:42).
	PSKcLen = 16
)

The sizes of connectedhomeip's dataset view (src/lib/support/ThreadOperationalDataset.h:36-42 at 6170af84).

Variables

View Source
var (
	// ErrThreadTLV is a MeshCoP TLV stream that cannot be walked: a
	// truncated header, extended-length header or value.
	//
	// Mirrors matter.js packages/protocol/src/thread/BasicTlvCodec.ts:9-10
	// (ThreadTlvError).
	ErrThreadTLV = errors.New("thread: malformed MeshCoP TLV stream")

	// ErrThreadDataset is an operational dataset whose TLV stream walks but
	// whose content does not decode: a fixed-width TLV of the wrong length,
	// a security policy that is not four bytes, or hex that does not parse.
	//
	// Mirrors matter.js packages/protocol/src/thread/errors.ts:9-10
	// (ThreadDatasetError).
	ErrThreadDataset = errors.New("thread: malformed operational dataset")

	// ErrInvalidTLV is an entry [EncodeTLVs] cannot write: a value longer
	// than 0xFFFF bytes.
	//
	// Mirrors the InternalError of matter.js
	// packages/protocol/src/thread/BasicTlvCodec.ts:54-64 (BasicTlv.encode).
	ErrInvalidTLV = errors.New("thread: TLV cannot be encoded")
)
View Source
var (
	// ErrInvalidDataset is a blob [NewDatasetView] refuses: chip's
	// CHIP_ERROR_INVALID_ARGUMENT from OperationalDatasetView::Init
	// (src/lib/support/ThreadOperationalDataset.cpp:166-171 at 6170af84).
	ErrInvalidDataset = errors.New("thread: not a framed operational dataset")
	// ErrTLVNotFound is a sub-TLV the dataset does not carry: chip's
	// CHIP_ERROR_TLV_TAG_NOT_FOUND of the getters (:196, :205, …).
	ErrTLVNotFound = errors.New("thread: dataset sub-TLV not found")
	// ErrTLVInvalid is a sub-TLV of a size chip's getter refuses: its
	// CHIP_ERROR_INVALID_TLV_ELEMENT (:197, :206-208, …).
	ErrTLVInvalid = errors.New("thread: dataset sub-TLV of an invalid size")
)

Functions

func EncodeTLVs

func EncodeTLVs(entries []TLV) ([]byte, error)

EncodeTLVs writes entries as a MeshCoP TLV stream, a value of 255 bytes or more in the extended-length form. A value over 0xFFFF bytes fails with ErrInvalidTLV.

Mirrors matter.js packages/protocol/src/thread/BasicTlvCodec.ts:54-84 (encode).

func ValidDataset

func ValidDataset(blob []byte) bool

ValidDataset is connectedhomeip's OperationalDatasetView::IsValid (src/lib/support/ThreadOperationalDataset.cpp:151-164 at 6170af84): at most MaxDatasetLen bytes, every TLV inside the blob, none in the extended-length form (a length byte of 0xFF, ThreadTLV::kLengthEscape, :47, "not allowed in a dataset TLV"). The empty blob is valid.

Types

type ChildTableEntry

type ChildTableEntry struct {
	TimeoutExponent     uint8
	TimeoutSeconds      uint32
	IncomingLinkQuality uint8
	ChildID             uint16
	Mode                Mode
}

ChildTableEntry is one child of a Child Table record (tlv/diag/ChildTable.ts:20-28).

type DatasetView

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

DatasetView reads an operational dataset the way connectedhomeip's OperationalDatasetView does (src/lib/support/ThreadOperationalDataset.cpp :149-310 at 6170af84): each getter takes the first sub-TLV of its type (DatasetView.Locate) and holds it to the size chip demands. It is the view a server checks a dataset with — the Thread Network Directory, the Thread Border Router Management cluster — where DecodeDataset, the commissioner's codec after matter.js, reads the last occurrence and accepts the one-byte Channel real border routers emit. A DatasetView shares its bytes with the blob it was made from.

func NewDatasetView

func NewDatasetView(blob []byte) (DatasetView, error)

NewDatasetView is OperationalDatasetView::Init (:166-171): the view of a blob ValidDataset accepts, ErrInvalidDataset otherwise.

func (DatasetView) ActiveTimestamp

func (v DatasetView) ActiveTimestamp() (uint64, error)

ActiveTimestamp is GetActiveTimestamp (:193-200): eight bytes, big-endian.

func (DatasetView) Bytes

func (v DatasetView) Bytes() []byte

Bytes is the dataset the view reads.

func (DatasetView) Channel

func (v DatasetView) Channel() (uint16, error)

Channel is GetChannel (:202-211): the three-byte form on channel page 0 only.

func (DatasetView) ChannelMask

func (v DatasetView) ChannelMask() ([]byte, error)

ChannelMask is GetChannelMask (:285-292): a non-empty value.

func (DatasetView) DelayTimer

func (v DatasetView) DelayTimer() (uint32, error)

DelayTimer is GetDelayTimer (:303-310): four bytes, big-endian milliseconds.

func (DatasetView) ExtPANID

func (v DatasetView) ExtPANID() ([]byte, error)

ExtPANID is GetExtendedPanIdAsByteSpan (:230-237): ExtPANIDLen bytes, sharing the view's memory.

func (DatasetView) Has

func (v DatasetView) Has(t TLVType) bool

Has reports whether the dataset carries a sub-TLV of type t (OperationalDatasetView::Has, ThreadOperationalDataset.h:239).

func (DatasetView) IsCommissioned

func (v DatasetView) IsCommissioned() bool

IsCommissioned is OperationalDatasetView::IsCommissioned (:188-191): the dataset carries the PAN ID, the Network Key, the Extended PAN ID and the Channel.

func (DatasetView) Locate

func (v DatasetView) Locate(t TLVType) ([]byte, bool)

Locate is OperationalDatasetView::Locate (:173-186): the value of the first sub-TLV of type t; false when there is none.

func (DatasetView) MeshLocalPrefix

func (v DatasetView) MeshLocalPrefix() ([]byte, error)

MeshLocalPrefix is GetMeshLocalPrefix (:239-246): MeshLocalPrefixLen bytes.

func (DatasetView) NetworkKey

func (v DatasetView) NetworkKey() ([]byte, error)

NetworkKey is GetMasterKey (:248-255): NetworkKeyLen bytes.

func (DatasetView) NetworkName

func (v DatasetView) NetworkName() (string, error)

NetworkName is GetNetworkName (:257-265): at most MaxNetworkNameLen bytes; chip checks no minimum.

func (DatasetView) PANID

func (v DatasetView) PANID() (uint16, error)

PANID is GetPanId (:267-274): two bytes, big-endian.

func (DatasetView) PSKc

func (v DatasetView) PSKc() ([]byte, error)

PSKc is GetPSKc (:276-283): PSKcLen bytes.

func (DatasetView) SecurityPolicy

func (v DatasetView) SecurityPolicy() (SecurityPolicy, error)

SecurityPolicy is GetSecurityPolicy (:294-301): four bytes, the rotation time and the flags.

type DeviceRole

type DeviceRole string

DeviceRole is a Thread node's role: the string the border router's REST surface answers on /node/state and in /node (OtbrRestClient.ts:275-282, "router", "leader", "child", "disabled"). It is the otDeviceRole that connectedhomeip maps to the RoutingRole attribute (DirectThreadNetworkDiagnosticsProvider.cpp:104-145 at 6170af84).

const (
	RoleDisabled DeviceRole = "disabled"
	RoleDetached DeviceRole = "detached"
	RoleChild    DeviceRole = "child"
	RoleRouter   DeviceRole = "router"
	RoleLeader   DeviceRole = "leader"
)

The roles of otDeviceRole.

func (DeviceRole) Attached

func (r DeviceRole) Attached() bool

Attached reports whether the role is one of an attached node: neither disabled nor detached — the completion an activation waits for (ADR 0027 decision 4; GenericThreadBorderRouterDelegate.cpp:145-157 at 6170af84 completes on kConnectivity_Established).

type DiagnosticResponse

type DiagnosticResponse struct {
	ExtMACAddress []byte
	Rloc16        *uint16
	Mode          *Mode
	Route64       *Route64
	LeaderData    *LeaderData
	MacCounters   *MacCounters
	MleCounters   *MleCounters
	ChildTable    []ChildTableEntry
	// Version is the Thread Version TLV (DiagnosticResponse.ts:38).
	Version *uint16
}

DiagnosticResponse is one node's diagnostics record (diagnostic/DiagnosticResponse.ts:19-46), the subset this module reads: a nil field is a record the response did not carry.

type LeaderData

type LeaderData struct {
	PartitionID       uint32
	Weighting         uint8
	DataVersion       uint8
	StableDataVersion uint8
	LeaderRouterID    uint8
}

LeaderData is the Leader Data record (tlv/diag/LeaderData.ts:21-27; OtbrRestClient.ts:13-19).

type MacCounters

type MacCounters struct {
	IfInUnknownProtos  uint32
	IfInErrors         uint32
	IfOutErrors        uint32
	IfInUcastPkts      uint32
	IfInBroadcastPkts  uint32
	IfInDiscards       uint32
	IfOutUcastPkts     uint32
	IfOutBroadcastPkts uint32
	IfOutDiscards      uint32
}

MacCounters is the MAC Counters record, the RFC 2863 interface counters (tlv/diag/MacCounters.ts:17-27).

type MleCounters

type MleCounters struct {
	DisabledRole                  uint16
	DetachedRole                  uint16
	ChildRole                     uint16
	RouterRole                    uint16
	LeaderRole                    uint16
	AttachAttempts                uint16
	PartitionIDChanges            uint16
	BetterPartitionAttachAttempts uint16
	ParentChanges                 uint16
	TrackedTime                   uint64
	DisabledTime                  uint64
	DetachedTime                  uint64
	ChildTime                     uint64
	RouterTime                    uint64
	LeaderTime                    uint64
}

MleCounters is the MLE Counters record (tlv/diag/MleCounters.ts:24-40): the role counts and the time in each role in milliseconds.

type Mode

type Mode struct {
	RxOnWhenIdle     bool
	FullThreadDevice bool
	FullNetworkData  bool
}

Mode is the MLE Mode record (tlv/diag/Mode.ts:21-25).

type NodeDiagnostics

type NodeDiagnostics struct {
	Role       DeviceRole
	ExtAddress []byte
	Rloc16     uint16
	LeaderData LeaderData
	Self       *DiagnosticResponse
	Mesh       []DiagnosticResponse
}

NodeDiagnostics is what a Thread Border Router reports about itself: its role, addresses and leader data (OTBR REST /node, OtbrRestClient.ts: 21-32), the diagnostics record it serves about itself (Self, nil when it serves none) and every record of the mesh it last collected (Mesh, Self among them), which names the extended addresses of the routers and children its own record lists by RLOC16.

type OperationalDataset

type OperationalDataset struct {
	// Channel is the channel number; the channel page of the three-byte
	// form is not kept.
	Channel          *uint16
	PANID            *uint16
	ExtPANID         []byte
	NetworkName      *string
	PSKc             []byte
	NetworkKey       []byte
	MeshLocalPrefix  []byte
	SecurityPolicy   *SecurityPolicy
	ActiveTimestamp  []byte
	PendingTimestamp []byte
	DelayTimer       *uint32
	ChannelMask      []byte
	UnknownTLVs      []TLV
	Raw              []byte
	// contains filtered or unexported fields
}

OperationalDataset is a decoded Thread operational dataset. Each named field is one MeshCoP TLV; nil is a TLV the dataset does not carry (an empty, non-nil slice is a zero-length TLV). TLVs without a field survive in UnknownTLVs; Raw is a copy of the decoded bytes.

A dataset from DecodeDataset also keeps the decoded TLVs, so OperationalDataset.Encode reproduces the source bytes while no field moved.

Mirrors matter.js packages/protocol/src/thread/OperationalDataset.ts:15-42 (OperationalDataset); the replay state the WeakMap ORIGINAL_TLVS holds there (:105-110) is the unexported field.

func DecodeDataset

func DecodeDataset(blob []byte) (*OperationalDataset, error)

DecodeDataset decodes a MeshCoP TLV stream. A stream that does not walk fails with ErrThreadTLV, a known TLV of the wrong size with ErrThreadDataset. The dataset shares no memory with blob.

Mirrors matter.js packages/protocol/src/thread/OperationalDataset.ts:53-69 (OperationalDataset.decode), for bytes.

func DecodeDatasetHex

func DecodeDatasetHex(s string) (*OperationalDataset, error)

DecodeDatasetHex decodes a dataset given as hex, whitespace anywhere ignored. Hex that does not parse fails with ErrThreadDataset.

Mirrors matter.js packages/protocol/src/thread/OperationalDataset.ts:53-54 (OperationalDataset.decode), for a string: whitespace is the set of JavaScript's `\s`.

func (*OperationalDataset) Encode

func (ds *OperationalDataset) Encode() ([]byte, error)

Encode writes the dataset as a MeshCoP TLV stream. A dataset from DecodeDataset replays: the decoded TLVs in their order, each known TLV in its source bytes while its field still holds the decoded value and in canonical form once it moved; a cleared field drops its TLV, an unknown TLV no longer in UnknownTLVs is dropped, and a field set that the source did not carry follows, canonical, in type order. A dataset built in memory encodes canonically: the known TLVs in type order, then UnknownTLVs. A value over 0xFFFF bytes fails with ErrInvalidTLV.

Mirrors matter.js packages/protocol/src/thread/OperationalDataset.ts:83-89 (OperationalDataset.encode), encodeWithReplay (:182-221) and canonicalEntries (:225-236).

func (*OperationalDataset) Redact

func (ds *OperationalDataset) Redact() *OperationalDataset

Redact is a shallow copy of ds without PSKc, NetworkKey and Raw, the input untouched: a value that is safe to log. The copy carries no replay state, so it encodes canonically.

Mirrors matter.js packages/protocol/src/thread/OperationalDataset.ts:100-102 (OperationalDataset.redact) at b25ed960 for PSKc and NetworkKey: the spread copy there is not in the ORIGINAL_TLVS WeakMap. It departs from it for Raw: the copy there keeps raw (:41), the source bytes and the network key and PSKc with them, under a doc that calls the result safe to log (:94); here Raw is dropped too (review II, R2-P6-sec-2022, notes/parity/by_design.md BD-Matter-OperationalDataset-RedactDropsRaw).

type Route64

type Route64 struct {
	IDSequence uint8
	Entries    []Route64Entry
}

Route64 is the Route64 record (tlv/diag/Route64.ts:39-42): the ID sequence and one entry per allocated router, in router-id order.

type Route64Entry

type Route64Entry struct {
	RouterID       uint8
	LinkQualityIn  uint8
	LinkQualityOut uint8
	RouteCost      uint8
}

Route64Entry is one router of a Route64 record (tlv/diag/Route64.ts:32-37).

type SecurityPolicy

type SecurityPolicy struct {
	RotationTime uint16
	Flags        uint16
}

SecurityPolicy is the MeshCoP Security Policy TLV (type 12): the key rotation time in hours and the raw 16-bit policy flags, whose bit layout depends on the Thread revision (Thread spec §8.10.1.15).

Mirrors matter.js packages/protocol/src/thread/SecurityPolicy.ts:10-21 (SecurityPolicy). Both fields are uint16, so the range checks of SecurityPolicy.encode (:36-41) are the Go type.

func DecodeSecurityPolicy

func DecodeSecurityPolicy(value []byte) (SecurityPolicy, error)

DecodeSecurityPolicy reads the four-byte TLV value: big-endian rotation time, then big-endian flags. Any other length fails with ErrThreadDataset.

Mirrors matter.js packages/protocol/src/thread/SecurityPolicy.ts:24-33 (SecurityPolicy.decode).

func (SecurityPolicy) Encode

func (p SecurityPolicy) Encode() []byte

Encode is the four-byte TLV value of p.

Mirrors matter.js packages/protocol/src/thread/SecurityPolicy.ts:35-48 (SecurityPolicy.encode).

type TLV

type TLV struct {
	Type  TLVType
	Value []byte
}

TLV is one frame of a MeshCoP TLV stream: [type:1][length:1][value], length 0xFF escaping to a two-byte big-endian length after it.

Mirrors matter.js packages/protocol/src/thread/BasicTlvCodec.ts:12-19 (BasicTlvEntry). The type is a byte, so the 0..255 range check of BasicTlv.encode (:57-59) is the Go type.

func WalkTLVs

func WalkTLVs(blob []byte) ([]TLV, error)

WalkTLVs splits a MeshCoP TLV stream into its frames, each value a copy. A truncated header, extended-length header or value fails with ErrThreadTLV; empty input is an empty stream.

Mirrors matter.js packages/protocol/src/thread/BasicTlvCodec.ts:22-52 (BasicTlv.walk).

type TLVType

type TLVType uint8

TLVType is a MeshCoP TLV type identifier (Thread 1.4 spec §8.10 plus the types of Agners' reference parser).

Mirrors matter.js packages/protocol/src/thread/meshcopTlvTypes.ts:14-58 (MeshCopTlvType), in its order.

const (
	TLVChannel                 TLVType = 0
	TLVPANID                   TLVType = 1
	TLVExtPANID                TLVType = 2
	TLVNetworkName             TLVType = 3
	TLVPSKc                    TLVType = 4
	TLVNetworkKey              TLVType = 5
	TLVNetworkKeySequence      TLVType = 6
	TLVMeshLocalPrefix         TLVType = 7
	TLVSteeringData            TLVType = 8
	TLVBorderAgentLocator      TLVType = 9
	TLVCommissionerID          TLVType = 10
	TLVCommissionerSessionID   TLVType = 11
	TLVSecurityPolicy          TLVType = 12
	TLVGet                     TLVType = 13
	TLVActiveTimestamp         TLVType = 14
	TLVCommissionerUDPPort     TLVType = 15
	TLVState                   TLVType = 16
	TLVJoinerDTLSEncapsulation TLVType = 17
	TLVJoinerUDPPort           TLVType = 18
	TLVJoinerIID               TLVType = 19
	TLVJoinerRouterLocator     TLVType = 20
	TLVJoinerRouterKEK         TLVType = 21
	TLVDuration                TLVType = 23
	TLVProvisioningURL         TLVType = 32
	TLVVendorName              TLVType = 33
	TLVVendorModel             TLVType = 34
	TLVVendorSWVersion         TLVType = 35
	TLVVendorData              TLVType = 36
	TLVVendorStackVersion      TLVType = 37
	TLVUDPEncapsulation        TLVType = 48
	TLVIPv6Address             TLVType = 49
	TLVPendingTimestamp        TLVType = 51
	TLVDelayTimer              TLVType = 52
	TLVChannelMask             TLVType = 53
	TLVCount                   TLVType = 54
	TLVPeriod                  TLVType = 55
	TLVScanDuration            TLVType = 56
	TLVEnergyList              TLVType = 57
	TLVThreadDomainName        TLVType = 59
	TLVWakeupChannel           TLVType = 74
	TLVDiscoveryRequest        TLVType = 128
	TLVDiscoveryResponse       TLVType = 129
	TLVJoinerAdvertisement     TLVType = 241
)

The MeshCoP TLV types; TLVType.Name gives each its matter.js name.

func (TLVType) Name

func (t TLVType) Name() (name string, ok bool)

Name is the matter.js name of a MeshCoP TLV type ("CHANNEL", "NETWORK_NAME", …), for diagnostics; ok is false for a type the table does not know.

Mirrors matter.js packages/protocol/src/thread/meshcopTlvTypes.ts:63-69 (MeshCopTlvTypeName).

Directories

Path Synopsis
Package brdiscovery is a passive registry of the Thread border routers on the LAN, discovered over DNS-SD: a port of matter.js packages/thread-br-client/src/discovery/BorderRouterRegistry.ts at b25ed960 for the fields a network topology needs.
Package brdiscovery is a passive registry of the Thread border routers on the LAN, discovered over DNS-SD: a port of matter.js packages/thread-br-client/src/discovery/BorderRouterRegistry.ts at b25ed960 for the fields a network topology needs.
Package otbr reaches an OpenThread Border Router (ot-br-posix) over its REST API and adapts it to the Thread Border Router port of the cluster servers (cluster/threadbr BorderRouter, ADR 0027 decision 4).
Package otbr reaches an OpenThread Border Router (ot-br-posix) over its REST API and adapts it to the Thread Border Router port of the cluster servers (cluster/threadbr BorderRouter, ADR 0027 decision 4).
otbrtest
Package otbrtest is an OpenThread Border Router's REST surface in process, for the tests of thread/otbr and of the Thread Border Router servers on it: an httptest server that answers the endpoints thread/otbr reads and writes, after the recorded responses of matter.js packages/thread-br-client/test/fixtures/otbr-rest/ at 862ad75f (fixtures.go) and the routing mock of OtbrRestClientTest.ts (MockOtbrServer, :51-94), with the behaviour of an ot-br-posix agent the writes need: a Thread interface that attaches after an enable, a 409 for a dataset replaced or deleted while it is up.
Package otbrtest is an OpenThread Border Router's REST surface in process, for the tests of thread/otbr and of the Thread Border Router servers on it: an httptest server that answers the endpoints thread/otbr reads and writes, after the recorded responses of matter.js packages/thread-br-client/test/fixtures/otbr-rest/ at 862ad75f (fixtures.go) and the routing mock of OtbrRestClientTest.ts (MockOtbrServer, :51-94), with the behaviour of an ot-br-posix agent the writes need: a Thread interface that attaches after an enable, a 409 for a dataset replaced or deleted while it is up.

Jump to

Keyboard shortcuts

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