Refactoring for fractional-value stamp support

This commit is contained in:
Mark Qvist 2026-10-30 00:52:50 +01:00
parent 75465efad8
commit 796ef2d44b
No known key found for this signature in database
8 changed files with 48 additions and 49 deletions

View file

@ -43,7 +43,7 @@ def server(configpath):
)
# We can optionally configure a link request stamp cost
server_destination.set_link_cost(14)
server_destination.set_link_cost(14.2)
# We configure a function that will get called every time
# a new client creates a link to this destination.

View file

@ -36,6 +36,7 @@ import RNS
from RNS.Cryptography import Token
from RNS.Stamps import generate_stamp, store_destination_stamp, load_destination_stamp
from RNS.Stamps import cost_to_bytes, quantize_cost
from .vendor import umsgpack as umsgpack
class Callbacks:
@ -163,7 +164,7 @@ class Destination:
self.stamp = None
self.stamp_value = None
self._target_value = RNS.Transport.DESTINATION_VALUE
self.link_cost = None
self._link_cost = None
self.ratchets = None
self.ratchets_path = None
self.ratchet_interval = Destination.RATCHET_INTERVAL
@ -316,7 +317,7 @@ class Destination:
app_data = returned_app_data
if RNS.Transport.STAMP_DESTINATIONS:
if self.stamp == None or self.stamp_value == None or self.stamp_value < self.target_value:
if self.stamp == None or self.stamp_value == None or self.stamp_value < quantize_cost(self.target_value):
stamp_entry = load_destination_stamp(self.hash, self.stamp_material(), self.target_value)
if stamp_entry != None: self.stamp, self.stamp_value = stamp_entry
else:
@ -331,7 +332,9 @@ class Destination:
store_destination_stamp(self.hash, stamp, stamp_value)
RNS.log(f"Generated and persisted stamp with value {self.stamp_value} for {self}", RNS.LOG_DEBUG)
ext_payload = bytes([RNS.Identity.EXTPAYLOADMARKER, self.get_ext_flags()])+self.stamp+bytes([self.get_link_cost()])
cost_bytes = cost_to_bytes(self.get_link_cost())
ext_payload = bytes([RNS.Identity.EXTPAYLOADMARKER, self.get_ext_flags()])+self.stamp+bytes([cost_bytes[1], cost_bytes[0]])
if app_data == None: app_data = ext_payload
else: app_data = app_data+ext_payload
@ -365,35 +368,35 @@ class Destination:
@property
def target_value(self):
return min(RNS.Transport.STAMP_COST_CAP, max(int(self._target_value), RNS.Transport.DESTINATION_VALUE))
return min(RNS.Transport.STAMP_COST_CAP, max(float(self._target_value), RNS.Transport.DESTINATION_VALUE))
def set_value(self, value):
"""
Sets the target stamp value for this destination.
:param value: The target value as an *integer*.
:param value: The target value as a *float*.
"""
self._target_value = min(RNS.Transport.STAMP_COST_CAP, max(int(value), RNS.Transport.DESTINATION_VALUE))
self._target_value = min(RNS.Transport.STAMP_COST_CAP, max(float(value), RNS.Transport.DESTINATION_VALUE))
def set_link_cost(self, cost):
"""
Sets the required link establishment stamp cost for this destination. Set to 0 to disable.
:param cost: The required cost as an *integer*.
:param cost: The required cost as a *float*.
"""
self.link_cost = max(0, min(int(cost), RNS.Transport.LINK_COST_CAP))
self._link_cost = max(0, min(float(cost), RNS.Transport.LINK_COST_CAP))
def get_link_cost(self):
"""
Returns the link request stamp cost to be announced for this
destination, as an integer. If no destination-specific cost has
destination, as a float. If no destination-specific cost has
been set, the default link request cost is returned.
:returns: The announced link request cost as an *integer*.
:returns: The announced link request cost as a *float*.
"""
cost = self.link_cost
cost = self._link_cost
if cost == None: cost = RNS.Transport.LR_COST
return max(0, min(int(cost), RNS.Transport.STAMP_COST_CAP))
return max(0.0, min(float(cost), RNS.Transport.STAMP_COST_CAP))
def accepts_links(self, accepts = None):
"""

View file

@ -330,7 +330,6 @@ class InterfaceAnnounceHandler:
self.invalid_cache.append(fullhash)
return
if value < self.required_value: RNS.log(f"Ignored discovered interface with stamp value {value}", RNS.LOG_DEBUG)
else:
info = None
unpacked = msgpack.unpackb(packed)

View file

@ -41,7 +41,7 @@ from .vendor import umsgpack as umsgpack
from RNS.Cryptography import X25519PrivateKey, X25519PublicKey, Ed25519PrivateKey, Ed25519PublicKey
from RNS.Cryptography import Token
from RNS.Storage import KnownDestinationsStore
from RNS.Stamps import stamp_workblock, stamp_valid, stamp_value, generate_stamped_key
from RNS.Stamps import stamp_workblock, stamp_valid, stamp_value, generate_stamped_key, cost_from_bytes
class Identity:
@ -84,7 +84,7 @@ class Identity:
SIGLENGTH = KEYSIZE # In bits
STAMPLENGTH = 14 # In bytes
EXTHEADERLENGTH = 2 # In bytes
LRCOSTLENGTH = 1 # In bytes
LRCOSTLENGTH = 2 # In bytes
EXTPAYLOADLENGTH = EXTHEADERLENGTH+STAMPLENGTH+LRCOSTLENGTH
EXTPAYLOADMARKER = 0xC1 # Never used at msgpack object boundaries
@ -191,7 +191,7 @@ class Identity:
Recall last heard announce stamp value for a destination hash.
:param destination_hash: Destination hash as *bytes*.
:returns: *Integer*, or *None* if the destination is unknown.
:returns: *Float*, or *None* if the destination is unknown.
"""
known_destination = Identity.known_destinations.get(destination_hash)
if not known_destination: return None
@ -203,7 +203,7 @@ class Identity:
Recall the link request stamp cost announced by a destination.
:param destination_hash: Destination hash as *bytes*.
:returns: *Integer*, or *None* if the destination is unknown or has not announced a cost.
:returns: *Float*, or *None* if the destination is unknown or has not announced a cost.
"""
known_destination = Identity.known_destinations.get(destination_hash)
if not known_destination: return None
@ -724,21 +724,19 @@ class Identity:
ext_flags = ext_header[1] # Reserved for future extensions
ext_anchor = ext_payload[-1]
# The trailing anchor byte carries the announced link request stamp
# cost in its 7 least significant bits, and an extension marker in
# its most significant bit. If the extension marker is set, the
# ext_payload is of a newer and potentially longer format, parsed
# through versioned logic not yet implemented in this version, and
# must not be interpreted here. As long as announced costs cannot
# exceed STAMP_COST_CAP, valid announce ext_payloads will always
# present with the extension marker cleared.
ext_extended = (ext_anchor & 0x80) != 0
ext_lr_cost = ext_anchor & 0x7F
known_format = (not ext_extended) and (ext_lr_cost <= RNS.Transport.STAMP_COST_CAP)
# The ext_anchor carries the lr_cost integer part, and a
# reserved flag in the MSB. The fractional part of the
# lr_cost is stored in the immediately preceding byte.
ext_extended = (ext_anchor & 0x80) != 0
ext_lr_cost_i = ext_anchor & 0x7F
ext_lr_cost_m = ext_payload[-2]
cost_bytes = bytes([ext_lr_cost_i, ext_lr_cost_m])
ext_lr_cost = cost_from_bytes(cost_bytes)
known_format = (not ext_extended) and (ext_lr_cost <= RNS.Transport.STAMP_COST_CAP)
if (not ext_header[0] == Identity.EXTPAYLOADMARKER) or (not known_format): dst_stamped = False
else:
# RNS.log(f"Checking potential stamp in announce with app_data len {len(app_data)} for {RNS.prettyhexrep(destination_hash)}", RNS.LOG_DEBUG) # TODO: Remove
# RNS.log(f"Checking potential stamp in announce with app_data len {len(app_data)} for {RNS.prettyhexrep(destination_hash)}", RNS.LOG_DEBUG) # TODO: Remove after 1.6.1
dst_stamped = True
try:
stamp = ext_payload[Identity.EXTHEADERLENGTH:Identity.EXTHEADERLENGTH+Identity.STAMPLENGTH]
@ -983,7 +981,7 @@ class Identity:
def get_value(self):
"""
:returns: The stamp value of this identity as an *integer*
:returns: The stamp value of this identity as a *float*
"""
if not self.get_public_key(): return None
else: return stamp_value(self.sig_pub_bytes, self.pub_bytes)

View file

@ -192,8 +192,7 @@ class Link:
stamp_material = owner.hash + peer_sig_pub_bytes
value = stamp_value(stamp_material, peer_pub_bytes)
RNS.log(f"Incoming LR value: {value}", RNS.LOG_DEBUG) # TODO: Remove
if RNS.Transport.LR_STAMPS_ENFORCED and value < owner.get_link_cost(): raise ValueError(f"Insufficient link request stamp value {value}")
if RNS.Transport.LR_STAMPS_ENFORCED and stamp_valid(peer_pub_bytes, owner.get_link_cost(), stamp_material): raise ValueError(f"Insufficient link request stamp value {value}")
link = Link(owner=owner, peer_pub_bytes=peer_pub_bytes, peer_sig_pub_bytes=peer_sig_pub_bytes)
link.set_link_id(packet)
@ -322,8 +321,6 @@ class Link:
self.sig_pub = self.sig_prv.public_key()
self.sig_pub_bytes = self.sig_pub.public_bytes()
else: RNS.log(f"Stamped link request, deferring key generation", RNS.LOG_DEBUG) # TODO: Remove
if peer_pub_bytes == None:
self.peer_pub = None
self.peer_pub_bytes = None
@ -360,7 +357,7 @@ class Link:
self.sig_pub_bytes = self.sig_pub.public_bytes()
self.stamp_material = self.destination.hash + self.sig_pub_bytes
RNS.log(f"Starting stamp generation for link request to {self.destination}", RNS.LOG_DEBUG) # TODO: Remove
RNS.log(f"Starting stamp generation for link request to {self.destination}", RNS.LOG_DEBUG)
self.stamp_job_id = self.stamp_material
threading.Thread(target=stamp_watchdog, daemon=True).start()
stamped_key, v = generate_stamped_key(material=self.stamp_material, stamp_cost=self.stamp_cost)
@ -396,9 +393,8 @@ class Link:
nh_hw_mtu = RNS.Transport.next_hop_interface_hw_mtu(self.destination.hash)
if RNS.Reticulum.link_mtu_discovery() and nh_hw_mtu:
signalling_bytes = Link.signalling_bytes(nh_hw_mtu, self.mode)
RNS.log(f"Signalling link MTU of {RNS.prettysize(nh_hw_mtu)} for link", RNS.LOG_DEBUG) # TODO: Remove debug
RNS.log(f"Signalling link MTU of {RNS.prettysize(nh_hw_mtu)} for link", RNS.LOG_PATHING) if RNS.sl(RNS.LOG_PATHING) else None
else: signalling_bytes = Link.signalling_bytes(RNS.Reticulum.MTU, self.mode)
RNS.log(f"Establishing link with mode {Link.MODE_DESCRIPTIONS[self.mode]}", RNS.LOG_DEBUG) # TODO: Remove debug
request_data = self.pub_bytes+self.sig_pub_bytes+signalling_bytes
self.packet = RNS.Packet(self.destination, request_data, packet_type=RNS.Packet.LINKREQUEST)
self.packet.pack()

View file

@ -492,23 +492,23 @@ class Reticulum:
if value == True: RNS.Transport.ALWAYS_STAMP_LRS = True
if option == "destination_cost":
v = self.config["stamps"].as_int(option)
v = self.config["stamps"].as_float(option)
RNS.Transport.DESTINATION_COST = max(0, min(v, RNS.Transport.STAMP_COST_CAP))
if option == "destination_value":
v = self.config["stamps"].as_int(option)
v = self.config["stamps"].as_float(option)
RNS.Transport.DESTINATION_VALUE = max(0, min(v, RNS.Transport.STAMP_COST_CAP))
if option == "pr_cost":
v = self.config["stamps"].as_int(option)
v = self.config["stamps"].as_float(option)
RNS.Transport.PR_COST = max(0, min(v, RNS.Transport.STAMP_COST_CAP))
if option == "pr_value":
v = self.config["stamps"].as_int(option)
v = self.config["stamps"].as_float(option)
RNS.Transport.PR_VALUE = max(0, min(v, RNS.Transport.STAMP_COST_CAP))
if option == "lr_cost":
v = self.config["stamps"].as_int(option)
v = self.config["stamps"].as_float(option)
RNS.Transport.LR_COST = max(0, min(v, RNS.Transport.LINK_COST_CAP))
if option == "lr_stamp_timeout":
@ -645,7 +645,7 @@ class Reticulum:
if v == False: Reticulum.__discover_interfaces = False
if option == "required_discovery_value":
v = self.config["reticulum"].as_int(option)
v = self.config["reticulum"].as_float(option)
if v > 0: Reticulum.__required_discovery_value = v
else: Reticulum.__required_discovery_value = None
@ -1050,7 +1050,7 @@ class Reticulum:
if discovery_announce_interval < 5*60: discovery_announce_interval = 5*60
if discovery_announce_interval == None: discovery_announce_interval = 6*60*60
if "discovery_stamp_value" in c: discovery_stamp_value = c.as_int("discovery_stamp_value")
if "discovery_stamp_value" in c: discovery_stamp_value = c.as_float("discovery_stamp_value")
if "discovery_name" in c: discovery_name = c["discovery_name"]
if "discovery_encrypt" in c: discovery_encrypt = c.as_bool("discovery_encrypt")
if "reachable_on" in c: reachable_on = c["reachable_on"]
@ -2182,7 +2182,7 @@ class Reticulum:
Returns the required stamp value for a discovered interface
to be considered valid and remembered.
:returns: The required stamp value as an integer.
:returns: The required stamp value as a float.
"""
return Reticulum.__required_discovery_value

View file

@ -809,6 +809,9 @@ def cost_from_fp(fp):
def cost_from_bytes(b):
return cost_from_fp(fp_from_bytes(b))
def quantize_cost(cost):
return cost_from_fp(cost_to_fp(cost))
def target_from_fp(fp):
assert 0 <= fp <= RNS.Transport.STAMP_COST_CAP * COST_FP
# Extract the integer and fractional parts

View file

@ -253,8 +253,8 @@ class KnownDestinationsStore:
app_data BLOB,
used REAL NOT NULL DEFAULT 0,
stamp BLOB,
stamp_value INTEGER,
lr_cost INTEGER,
stamp_value REAL,
lr_cost REAL,
identity_hash BLOB NOT NULL)""")
self._conn.execute("""CREATE TABLE IF NOT EXISTS ratchets (
@ -262,7 +262,7 @@ class KnownDestinationsStore:
ratchet BLOB NOT NULL,
received REAL NOT NULL)""")
if 0 < db_version < 2: self._conn.execute("ALTER TABLE known_destinations ADD COLUMN lr_cost INTEGER")
if 0 < db_version < 2: self._conn.execute("ALTER TABLE known_destinations ADD COLUMN lr_cost REAL")
self._conn.execute("PRAGMA user_version = 2")
self._conn.commit()