Signed-off-by: Jakob Borg <[email protected]>
This commit is contained in:
Jakob Borg committed 2026-11-29 11:13:00 +01:00
1 parent 9f5ea0a920
commit 7132c8fcdd
5 files changed
+62 -34

No files matched your search

+1 -3
View File
@@ -73,9 +73,7 @@ func checkServers(deviceID protocol.DeviceID, timeout time.Duration, bootstrapPe
wg.Go(func() {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
addresses, err := dht.Lookup(ctx, deviceID, dht.Options{
BootstrapPeers: bootstrapPeers,
})
addresses, err := dht.Lookup(ctx, deviceID, bootstrapPeers)
resc <- checkResult{server: "DHT", addresses: addresses, error: err}
})
+54 -24
View File
@@ -49,12 +49,15 @@ const (
p2pProtocolID = p2pProtocolPrefix + "/kad/1.0.0"
)
var ErrP2PNotFound = errors.New("peer-to-peer discovery record not found")
var (
errNotFound = errors.New("discovery record not found")
errNoPeers = errors.New("no peers")
)
// Lookup is a utility function for creating a single-use DHT instance and
// performing a lookup, without starting the full discovery machinery.
func Lookup(ctx context.Context, deviceID protocol.DeviceID, options Options) ([]string, error) {
dht, err := NewSyncthingDHT(options)
func Lookup(ctx context.Context, deviceID protocol.DeviceID, bootstrapPeers []string) ([]string, error) {
dht, err := NewSyncthingDHT(Options{BootstrapPeers: bootstrapPeers})
if err != nil {
return nil, err
}
@@ -72,16 +75,41 @@ func Lookup(ctx context.Context, deviceID protocol.DeviceID, options Options) ([
}
type Options struct {
UDP *registry.UDPReuseManager
ListenAddresses []netip.AddrPort
BootstrapPeers []string
AdvertiseAddresses []string
Identity []byte
ForceServer bool
ClientOnly bool
ValueDatastore *db.Typed
RoutingDatastore *db.Typed
MaxConnections int
// UDPReuseManager for sharing an UDP socket with BEP QUIC connections
UDP *registry.UDPReuseManager
// Listen addresses for incoming QUIC connections; required for server
// mode
ListenAddresses []netip.AddrPort
// Set of bootstrap peers for initial connection, in libp2p "multiaddr"
// string format
BootstrapPeers []string
// Set of listen addresses to announce to peers, in libp2p "multiaddr"
// string format (without /p2p/ ID)
AdvertiseAddresses []string
// Private Ed25519 key to use as libp2p identity
Identity []byte
// Set to force server mode, assuming global reachability
ForceServer bool
// Set to enforce client mode, the opposite of ForceServer
ClientOnly bool
// Data store for peer discovery records (server mode); use nil to not
// persist records
ValueDatastore *db.Typed
// Data store for routing table; use nil to not persist routing table
RoutingDatastore *db.Typed
// Max number of allowed peer connections total, zero for default
MaxConnections int
// Max number of allowed peer connections per subnet, zero for default
MaxConnectionsPerSubnet int
}
@@ -244,13 +272,11 @@ func NewSyncthingDHT(options Options) (*DHT, error) {
opts := []kad.Option{
kad.BootstrapPeers(peers...),
kad.BootstrapOrder(kad.PersistedFirst), // try known non-bootstrap peers first when starting up
kad.DisableProviders(), // we do not use IPFS provider records
kad.MaxRecordAge(RecordLifetime), // max time we keep a discovery record
kad.ValueGCInterval(RecordLifetime), // how often to run GC
kad.Mode(mode), // client/server/auto
kad.ProtocolPrefix(p2pProtocolPrefix), // "/syncthing/kad/1.0.0"
kad.RoutingTablePersistence(5 * time.Minute), // how often to store peers to db
kad.DisableProviders(), // we do not use IPFS provider records
kad.MaxRecordAge(MaxRecordLifetime), // max time we keep a discovery record
kad.ValueGCInterval(MaxRecordLifetime), // how often to run GC
kad.Mode(mode), // client/server/auto
kad.ProtocolPrefix(p2pProtocolPrefix), // "/syncthing/kad/1.0.0"
// validate discovery records
kad.Validator(record.NamespacedValidator{dhtRecordNamespace: dhtRecordValidator{}}),
@@ -268,7 +294,11 @@ func NewSyncthingDHT(options Options) (*DHT, error) {
}
if options.RoutingDatastore != nil {
opts = append(opts, kad.Datastore(newDatastore(options.RoutingDatastore)))
opts = append(
opts, kad.Datastore(newDatastore(options.RoutingDatastore)),
kad.BootstrapOrder(kad.PersistedFirst), // try known non-bootstrap peers first when starting up
kad.RoutingTablePersistence(5*time.Minute), // how often to store peers to db
)
} else {
opts = append(opts, kad.Datastore(dssync.MutexWrap(ds.NewMapDatastore())))
}
@@ -347,12 +377,12 @@ func (s *DHT) Lookup(ctx context.Context, deviceID protocol.DeviceID) (addresses
if len(errs) > 0 {
return nil, errors.Join(errs...)
}
return nil, ErrP2PNotFound
return nil, errNotFound
}
func (s *DHT) Announce(ctx context.Context, deviceID protocol.DeviceID, addresses []string, certificate []byte, privateKey stdcrypto.Signer) error {
if s.ipfs.RoutingTable().Size() == 0 {
return errors.New("no discovery peers")
return errNoPeers
}
now := time.Now()
@@ -360,7 +390,7 @@ func (s *DHT) Announce(ctx context.Context, deviceID protocol.DeviceID, addresse
r := &discoproto.DHTPayload{
Certificate: certificate,
Addresses: addresses,
ExpiresUnix: uint64(now.Add(RecordLifetime).Unix()), //nolint:gosec // does not wrap
ExpiresUnix: uint64(now.Add(MaxRecordLifetime).Unix()), //nolint:gosec // does not wrap
TimeValue: timeValue,
}
value, err := encodeRecord(r, privateKey)
+3 -3
View File
@@ -61,7 +61,7 @@ func TestDiscoveryTimeValues(t *testing.T) {
if got := discoveryTimeValues(id, now); !slices.Equal(got, []uint64{tc.current, tc.previous}) {
t.Errorf("at cutoff: got %v, want [%d %d]", got, tc.current, tc.previous)
}
if got := discoveryTimeValues(id, now.Add(RecordLifetime)); !slices.Equal(got, []uint64{tc.current}) {
if got := discoveryTimeValues(id, now.Add(MaxRecordLifetime)); !slices.Equal(got, []uint64{tc.current}) {
t.Errorf("after previous record expires: got %v, want [%d]", got, tc.current)
}
})
@@ -276,7 +276,7 @@ func TestSignedRecord(t *testing.T) {
payload := &discoproto.DHTPayload{
Certificate: cert.Certificate[0],
Addresses: []string{"tcp://192.0.2.1:22000"},
ExpiresUnix: uint64(now.Add(RecordLifetime).Unix()),
ExpiresUnix: uint64(now.Add(MaxRecordLifetime).Unix()),
TimeValue: discoveryTimeValue(id, now),
}
key := dhtRecordKey(id, payload.TimeValue)
@@ -306,7 +306,7 @@ func TestSignedRecord(t *testing.T) {
t.Errorf("accepted record under incorrect key %q", wrongKey)
}
}
if _, err := validateRecord(key, value, now.Add(RecordLifetime+time.Second)); err == nil {
if _, err := validateRecord(key, value, now.Add(MaxRecordLifetime+time.Second)); err == nil {
t.Error("accepted expired record")
}
+3 -3
View File
@@ -28,7 +28,7 @@ import (
)
const (
RecordLifetime = 2 * time.Hour
MaxRecordLifetime = 2 * time.Hour
dhtSignatureDomain = "syncthing-dht-discovery-v1\x00"
dhtRecordKeySeed = "syncthing-dht-record-key-v1\x00"
@@ -54,7 +54,7 @@ func dhtRecordKey(id protocol.DeviceID, timeValue uint64) string {
// from that period can still be valid.
func discoveryTimeValues(id protocol.DeviceID, now time.Time) []uint64 {
current := discoveryTimeValue(id, now)
oldest := discoveryTimeValue(id, now.Add(-RecordLifetime))
oldest := discoveryTimeValue(id, now.Add(-MaxRecordLifetime))
if oldest != current {
return []uint64{current, oldest}
}
@@ -129,7 +129,7 @@ func validateRecord(key string, value []byte, now time.Time) (*discoproto.DHTPay
return nil, errors.New("invalid discovery expiration")
}
expires := time.Unix(int64(payload.ExpiresUnix), 0)
if now.After(expires) || expires.After(now.Add(4*RecordLifetime)) {
if now.After(expires) || expires.After(now.Add(4*MaxRecordLifetime)) {
return nil, errors.New("invalid discovery expiration")
}
+1 -1
View File
@@ -196,7 +196,7 @@ func (s *PeerToPeerDiscovery) Serve(ctx context.Context) error {
if err == nil {
published = addresses
// 20 - 35 minutes
next = time.Now().Add(dht.RecordLifetime/6 + rand.N(dht.RecordLifetime/8)) //nolint:gosec
next = time.Now().Add(dht.MaxRecordLifetime/6 + rand.N(dht.MaxRecordLifetime/8)) //nolint:gosec
} else {
next = time.Now().Add(announceErrorRetryInterval)
slog.Debug("Failed to announce", "error", err, "next", next)