mirror of
https://github.com/pollen-robotics/microduck.git
synced 2026-11-22 06:29:20 +08:00
Read a beta's SoC serial from the kernel, not U-Boot
Every beta board came up as duck-d041, with one voice and one chorale id. The beta image's U-Boot reads the OTP's cpu id three bytes early (0x07, not 0x0a), so its sixteen bytes stop just short of the per-chip ones and every chip in a lot gets the same device-tree serial (8b33c6e86a6a0c15 on both boards measured). The kernel reads from 0x0a: /proc/cpuinfo's Serial differs per board. robotd_params::serial is now the one reader: the declared board picks the source — device tree on zero3 (unchanged, so no Zero 3W is renamed or re-voiced), /proc/cpuinfo on beta. configd's name and sounds' voice seed both use it; mediad's hardware_id follows configd. A beta re-renders its voice bank on the next update, since ensure-bank sees a new seed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
42d258628b
commit
34b6e7dcd1
Generated
+2
@@ -751,6 +751,7 @@ dependencies = [
|
||||
"duck-ipc-proto",
|
||||
"futures",
|
||||
"libc",
|
||||
"robotd-params",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.11.0",
|
||||
@@ -4457,6 +4458,7 @@ dependencies = [
|
||||
"anyhow",
|
||||
"clap",
|
||||
"hound",
|
||||
"robotd-params",
|
||||
"sha2 0.11.0",
|
||||
]
|
||||
|
||||
|
||||
@@ -13,6 +13,8 @@ description = "Wifi and robot identity — the config service"
|
||||
# It stores no credentials. NetworkManager owns those.
|
||||
[dependencies]
|
||||
duck-ipc-proto = { path = "../duck-ipc-proto" }
|
||||
# The SoC serial, which is read from a different place on each board (`robotd_params::serial`).
|
||||
robotd-params = { path = "../robotd-params" }
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
# `process` is for reading the journal: `logs` spawns `journalctl` rather than linking libsystemd
|
||||
|
||||
+18
-65
@@ -15,25 +15,14 @@
|
||||
//! right — an address change orphans every bond under `/var/lib/bluetooth/<address>/` and
|
||||
//! invalidates the peripheral identifier a phone saved — but it is not this module's problem.)
|
||||
//!
|
||||
//! The serial comes out of the SoC's one-time-programmable fuses by way of the bootloader, so it
|
||||
//! survives a reflash, survives swapping the radio module, and needs no provisioning step to
|
||||
//! exist — which is what makes a hand-flashed board work. It is also readable *immediately*: a
|
||||
//! plain file, no root, no D-Bus, no waiting the ~73 seconds it takes `hci0` to appear on this
|
||||
//! board.
|
||||
|
||||
use std::path::Path;
|
||||
//! The serial comes out of the SoC's one-time-programmable fuses, so it survives a reflash,
|
||||
//! survives swapping the radio module, and needs no provisioning step to exist — which is what makes
|
||||
//! a hand-flashed board work. It is also readable *immediately*: a plain file, no root, no D-Bus, no
|
||||
//! waiting the ~73 seconds it takes `hci0` to appear on this board. Which file depends on the board,
|
||||
//! and [`robotd_params::serial`] says why.
|
||||
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
/// Where the bootloader leaves the SoC serial.
|
||||
///
|
||||
/// `/proc/device-tree/serial-number` rather than `/proc/cpuinfo`: both report the same value on
|
||||
/// this board (`bb7b734a7717ac41`), but the devicetree property is a generic binding that any
|
||||
/// board populating it satisfies, while `cpuinfo`'s `Serial` line is a per-architecture quirk of
|
||||
/// how the kernel chooses to print it. A future board on a different SoC is more likely to keep
|
||||
/// the first.
|
||||
const SERIAL_PATH: &str = "/proc/device-tree/serial-number";
|
||||
|
||||
/// The prefix every derived name carries.
|
||||
///
|
||||
/// Hardcoded rather than built from the hostname, which would give `radxa-zero3-7f3a` — longer
|
||||
@@ -46,24 +35,7 @@ const NAME_PREFIX: &str = "duck";
|
||||
/// caller falls back rather than failing: a robot with no serial must still come up with a working
|
||||
/// name.
|
||||
pub fn serial() -> Option<String> {
|
||||
serial_at(Path::new(SERIAL_PATH))
|
||||
}
|
||||
|
||||
/// [`serial`], against an arbitrary path so it can be tested off a board.
|
||||
pub fn serial_at(path: &Path) -> Option<String> {
|
||||
let raw = std::fs::read(path).ok()?;
|
||||
let text = String::from_utf8_lossy(&raw);
|
||||
|
||||
// Devicetree properties are NUL-terminated strings, and a property may hold several — so the
|
||||
// first NUL ends the value rather than being trailing junk to trim.
|
||||
let serial = text.split('\0').next()?.trim();
|
||||
|
||||
// A property that exists but is blank, or full of control characters, is no identity at all,
|
||||
// and it also reaches a client verbatim through `system.info`.
|
||||
if serial.is_empty() || !serial.chars().all(|c| c.is_ascii_graphic()) {
|
||||
return None;
|
||||
}
|
||||
Some(serial.to_owned())
|
||||
robotd_params::serial::soc_serial()
|
||||
}
|
||||
|
||||
/// The name a robot answers to before anyone has renamed it: `duck-7f3a`.
|
||||
@@ -90,37 +62,6 @@ pub fn default_name(serial: &str) -> String {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn write(dir: &Path, contents: &[u8]) -> std::path::PathBuf {
|
||||
let path = dir.join("serial-number");
|
||||
std::fs::write(&path, contents).unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
/// The real shape of the property on the board: the value, NUL-terminated.
|
||||
#[test]
|
||||
fn a_nul_terminated_property_reads_as_the_value() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = write(dir.path(), b"bb7b734a7717ac41\0");
|
||||
assert_eq!(serial_at(&path).as_deref(), Some("bb7b734a7717ac41"));
|
||||
}
|
||||
|
||||
/// `/proc/device-tree` is absent on a laptop, and that must be a fallback rather than a panic.
|
||||
#[test]
|
||||
fn a_missing_property_is_no_serial() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
assert_eq!(serial_at(&dir.path().join("absent")), None);
|
||||
}
|
||||
|
||||
/// A board that fills the property in with nothing has no identity, and saying so lets the
|
||||
/// caller fall back to the hostname instead of naming every such board `duck-e3b0`.
|
||||
#[test]
|
||||
fn a_blank_or_unprintable_property_is_no_serial() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
for raw in [&b""[..], b"\0", b" \0", b"\x01\x02\0"] {
|
||||
assert_eq!(serial_at(&write(dir.path(), raw)), None, "{raw:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The name has to be stable for the life of the board: it is what a phone remembers, and a
|
||||
/// robot that renames itself is one a kid has to find again. This pins the exact output for
|
||||
/// the serial the board actually has, so a change to the derivation fails here rather than in
|
||||
@@ -130,6 +71,18 @@ mod tests {
|
||||
assert_eq!(default_name("bb7b734a7717ac41"), "duck-c51b");
|
||||
}
|
||||
|
||||
/// Two beta boards from one lot, which both came up as `duck-d041` while their name was made
|
||||
/// from U-Boot's serial (`8b33c6e86a6a0c15` on both). The kernel's serials tell them apart.
|
||||
#[test]
|
||||
fn two_beta_boards_from_one_lot_get_two_names() {
|
||||
assert_eq!(default_name("8b33c6e86a6a0c15"), "duck-d041");
|
||||
assert_eq!(default_name("62285dd716c88f0f"), "duck-2b6d");
|
||||
assert_ne!(
|
||||
default_name("62285dd716c88f0f"),
|
||||
default_name("9ed5ef3c1c5ff3f1")
|
||||
);
|
||||
}
|
||||
|
||||
/// Two boards must not collide, which is the entire point.
|
||||
#[test]
|
||||
fn different_serials_give_different_names() {
|
||||
|
||||
@@ -816,12 +816,20 @@ one nobody can use, and that stands on its own. §8.1 is tracked separately and
|
||||
|
||||
#### What a robot is called
|
||||
|
||||
**Identity comes from the SoC serial**, read from `/proc/device-tree/serial-number` and reported by
|
||||
`system.info` (`configd::identity`). Fused into the chip and handed over by the bootloader, so it
|
||||
survives a reflash, survives swapping the radio module, and needs no provisioning step to exist —
|
||||
**Identity comes from the SoC serial**, reported by `system.info` (`configd::identity`). Fused into
|
||||
the chip, so it survives a reflash, survives swapping the radio module, and needs no provisioning step to exist —
|
||||
which is what keeps a hand-flashed board working. It is also a plain file read: no root, no D-Bus,
|
||||
and available immediately rather than after the ~73 seconds `hci0` takes to appear.
|
||||
|
||||
**Where it is read depends on the board** (`robotd_params::serial`). Rockchip's serial is a CRC of
|
||||
sixteen bytes of the SoC's OTP, computed twice: by U-Boot, into the device tree's `serial-number`,
|
||||
and by the kernel, into `/proc/cpuinfo`'s `Serial`. A zero3 reads the device tree, which is what
|
||||
every Zero 3W's name was made from. A beta reads `/proc/cpuinfo`: the beta image's U-Boot reads the
|
||||
OTP three bytes early (0x07, not 0x0a), stops just short of the per-chip bytes, and gives every chip
|
||||
in a lot the same serial — the first two beta boards were both `duck-d041`. The voice and the chorale
|
||||
id are seeded from the same value (`sounds::hardware_seed`), so they had collided too; and a beta
|
||||
whose kernel prints no `Serial` has no serial rather than the lot's.
|
||||
|
||||
This is not a new idea in this repository, which is worth saying: `updater-design.md` §5.6 already
|
||||
picked the same value as the update log's stable device ID, for the same reason — it works and needs
|
||||
no provisioning step to obtain. Reusing it means the robot has one identity rather than two.
|
||||
|
||||
@@ -628,9 +628,9 @@ rolled back for the state of the board it landed on.
|
||||
manual escape. Needs an API and a rule about who may call it
|
||||
([`app-path-design.md`](app-path-design.md) §5).
|
||||
7. **Per-device provisioning state** — the per-robot pairing PIN, and nothing else now. The serial
|
||||
was the other claimant and no longer needs a slot: it is fused into the SoC and read from
|
||||
`/proc/device-tree/serial-number` (`updater-design.md` §5.6,
|
||||
[`app-path-design.md`](app-path-design.md) §8.2). The PIN cannot share the identity, which was
|
||||
was the other claimant and no longer needs a slot: it is fused into the SoC
|
||||
(`updater-design.md` §5.6, [`app-path-design.md`](app-path-design.md) §8.2 says where it is
|
||||
read on each board). The PIN cannot share the identity, which was
|
||||
the plan: the identity is published in an advertisement, so anything derived from it is public.
|
||||
A secret still has to be generated, recorded and printed at manufacture.
|
||||
|
||||
|
||||
@@ -438,8 +438,8 @@ What the updater keeps is deliberately minimal:
|
||||
before the board was a setting carries `hw_rev = 1`, and a board provisioned against a
|
||||
release that still shipped it does too, so it cannot be allowed to outrank the board.
|
||||
- A **stable device ID** for the update log (§8.3) and any future phone-home. The
|
||||
SoC serial (`/proc/device-tree/serial-number`) works and survives reflashes —
|
||||
no provisioning step needed to obtain it.
|
||||
SoC serial works and survives reflashes — no provisioning step needed to obtain
|
||||
it. Where it is read differs per board ([`app-path-design.md`](app-path-design.md) §8.2).
|
||||
|
||||
#### Retiring a board
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
pub mod board;
|
||||
pub mod edit;
|
||||
pub mod registry;
|
||||
pub mod serial;
|
||||
|
||||
pub mod pad_axes;
|
||||
pub use pad_axes::{PadAxesParams, PadBodyParams, PadHeadParams, PadRollerParams};
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
//! The SoC serial: the per-chip value a robot's identity hangs off.
|
||||
//!
|
||||
//! Three things derive from it, and all three need it to differ between two robots: the default
|
||||
//! name (`configd::identity`), the voice and the chorale id (`sounds::hardware_seed`), and the
|
||||
//! `hardware_id` remote access registers under (`mediad`, through `system.info`). One reader here so
|
||||
//! that they cannot disagree about which value that is.
|
||||
//!
|
||||
//! **Where it is read depends on the board**, because the two places it can be read from are not
|
||||
//! the same value on every board. Both are Rockchip's derivation — a CRC of sixteen bytes of the
|
||||
//! SoC's OTP — computed twice: once by U-Boot, which hands it to the kernel as the device tree's
|
||||
//! `serial-number`, and once by the kernel's `rockchip-cpuinfo`, which prints it as `/proc/cpuinfo`'s
|
||||
//! `Serial`.
|
||||
//!
|
||||
//! - **zero3: the device tree.** That is what every Zero 3W's name and voice were derived from, and
|
||||
//! changing the source would rename them and change their voices.
|
||||
//! - **beta: `/proc/cpuinfo`.** The U-Boot on the beta images reads the OTP three bytes early, at
|
||||
//! 0x07 instead of 0x0a. Its sixteen bytes then end at 0x16, which is where the chip's model and
|
||||
//! lot end and the per-chip bytes begin, so every chip in a lot hashes to one value: two boards
|
||||
//! from Seeed's first batch both said `8b33c6e86a6a0c15` and both came up as `duck-d041`, with
|
||||
//! one voice, and one chorale id — which makes each duck drop the other's beacons as its own
|
||||
//! echo. The kernel reads from 0x0a, and those two boards said `62285dd716c88f0f` and
|
||||
//! `9ed5ef3c1c5ff3f1`. (Measured 2026-10-15 by hashing each board's OTP dump at both offsets.)
|
||||
//! A beta with no `Serial` line has no serial: falling back to the device tree would bring the
|
||||
//! collision back, so the callers' own fallbacks apply instead.
|
||||
//!
|
||||
//! The board is the declared one ([`Board::declared`]), as everywhere else that differs per board.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use crate::board::Board;
|
||||
|
||||
/// Where U-Boot leaves its serial.
|
||||
pub const DEVICE_TREE_PATH: &str = "/proc/device-tree/serial-number";
|
||||
|
||||
/// Where the kernel prints its own.
|
||||
pub const CPUINFO_PATH: &str = "/proc/cpuinfo";
|
||||
|
||||
/// This robot's SoC serial, or `None` where there is not one to read — a laptop, a board whose
|
||||
/// bootloader leaves the property out, a beta whose kernel prints no `Serial`.
|
||||
pub fn soc_serial() -> Option<String> {
|
||||
soc_serial_at(
|
||||
Board::declared(Path::new(crate::DEFAULT_PATH)).unwrap_or_default(),
|
||||
Path::new(DEVICE_TREE_PATH),
|
||||
Path::new(CPUINFO_PATH),
|
||||
)
|
||||
}
|
||||
|
||||
/// [`soc_serial`], for a given board and against arbitrary paths so it can be tested off one.
|
||||
pub fn soc_serial_at(board: Board, device_tree: &Path, cpuinfo: &Path) -> Option<String> {
|
||||
match board {
|
||||
Board::Zero3 => device_tree_serial(device_tree),
|
||||
Board::Beta => cpuinfo_serial(cpuinfo),
|
||||
}
|
||||
}
|
||||
|
||||
fn device_tree_serial(path: &Path) -> Option<String> {
|
||||
let raw = std::fs::read(path).ok()?;
|
||||
let text = String::from_utf8_lossy(&raw);
|
||||
// Devicetree properties are NUL-terminated strings, and a property may hold several — so the
|
||||
// first NUL ends the value rather than being trailing junk to trim.
|
||||
valid(text.split('\0').next()?)
|
||||
}
|
||||
|
||||
fn cpuinfo_serial(path: &Path) -> Option<String> {
|
||||
let text = std::fs::read_to_string(path).ok()?;
|
||||
let value = text.lines().find_map(|line| {
|
||||
let (key, value) = line.split_once(':')?;
|
||||
(key.trim() == "Serial").then_some(value)
|
||||
})?;
|
||||
// The kernel prints zeros when it found no OTP to read, and zeros are every such board.
|
||||
valid(value).filter(|serial| serial.chars().any(|c| c != '0'))
|
||||
}
|
||||
|
||||
/// A value that is blank, or full of control characters, is no identity at all — and it reaches a
|
||||
/// client verbatim through `system.info`.
|
||||
fn valid(value: &str) -> Option<String> {
|
||||
let serial = value.trim();
|
||||
(!serial.is_empty() && serial.chars().all(|c| c.is_ascii_graphic())).then(|| serial.to_owned())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The two sources as the beta board at 192.168.10.133 reports them.
|
||||
fn beta_133(dir: &Path) -> (std::path::PathBuf, std::path::PathBuf) {
|
||||
let device_tree = dir.join("serial-number");
|
||||
std::fs::write(&device_tree, b"8b33c6e86a6a0c15\0").unwrap();
|
||||
let cpuinfo = dir.join("cpuinfo");
|
||||
std::fs::write(
|
||||
&cpuinfo,
|
||||
"processor\t: 3\nBogoMIPS\t: 48.00\nCPU part\t: 0xd05\n\nSerial\t\t: 62285dd716c88f0f\n",
|
||||
)
|
||||
.unwrap();
|
||||
(device_tree, cpuinfo)
|
||||
}
|
||||
|
||||
/// The beta reads the kernel's value, not U-Boot's lot-wide one.
|
||||
#[test]
|
||||
fn a_beta_reads_the_kernels_serial() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (device_tree, cpuinfo) = beta_133(dir.path());
|
||||
assert_eq!(
|
||||
soc_serial_at(Board::Beta, &device_tree, &cpuinfo).as_deref(),
|
||||
Some("62285dd716c88f0f")
|
||||
);
|
||||
}
|
||||
|
||||
/// A Zero 3W keeps the value its name and voice were made from.
|
||||
#[test]
|
||||
fn a_zero3_reads_the_device_tree() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (device_tree, cpuinfo) = beta_133(dir.path());
|
||||
assert_eq!(
|
||||
soc_serial_at(Board::Zero3, &device_tree, &cpuinfo).as_deref(),
|
||||
Some("8b33c6e86a6a0c15")
|
||||
);
|
||||
}
|
||||
|
||||
/// A beta with no usable `Serial` has no serial — never the device tree's, which is the same on
|
||||
/// every board in a lot.
|
||||
#[test]
|
||||
fn a_beta_without_a_kernel_serial_has_none() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (device_tree, cpuinfo) = beta_133(dir.path());
|
||||
for text in [
|
||||
"processor\t: 0\n",
|
||||
"Serial\t\t: 0000000000000000\n",
|
||||
"Serial\t\t: \n",
|
||||
] {
|
||||
std::fs::write(&cpuinfo, text).unwrap();
|
||||
assert_eq!(
|
||||
soc_serial_at(Board::Beta, &device_tree, &cpuinfo),
|
||||
None,
|
||||
"{text:?}"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
soc_serial_at(Board::Beta, &device_tree, &dir.path().join("absent")),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
/// The device tree's property is NUL-terminated; blank or unprintable is no serial.
|
||||
#[test]
|
||||
fn a_device_tree_serial_is_the_first_string_and_must_be_printable() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("serial-number");
|
||||
let cpuinfo = dir.path().join("absent");
|
||||
std::fs::write(&path, b"bb7b734a7717ac41\0").unwrap();
|
||||
assert_eq!(
|
||||
soc_serial_at(Board::Zero3, &path, &cpuinfo).as_deref(),
|
||||
Some("bb7b734a7717ac41")
|
||||
);
|
||||
for raw in [&b""[..], b"\0", b" \0", b"\x01\x02\0"] {
|
||||
std::fs::write(&path, raw).unwrap();
|
||||
assert_eq!(
|
||||
soc_serial_at(Board::Zero3, &path, &cpuinfo),
|
||||
None,
|
||||
"{raw:?}"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
soc_serial_at(Board::Zero3, &dir.path().join("absent"), &cpuinfo),
|
||||
None
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -16,3 +16,5 @@ anyhow = "1"
|
||||
clap = { workspace = true, features = ["derive"] }
|
||||
hound.workspace = true
|
||||
sha2 = "0.11"
|
||||
# The SoC serial the voice is seeded from, read the same way configd reads it for the name.
|
||||
robotd-params = { path = "../robotd-params" }
|
||||
|
||||
+9
-12
@@ -125,9 +125,9 @@ pub fn render_all(p: &Personality, out_dir: &Path) -> Result<Vec<PathBuf>> {
|
||||
|
||||
/// The voice seed this hardware derives — the SoC's efuse serial hashed to a u32.
|
||||
///
|
||||
/// The serial is burned into the chip, survives reflashes, and the supported boards expose
|
||||
/// it at the same path. `/etc/machine-id` (unique per OS install) is the fallback for a
|
||||
/// board without one. sha256 decorrelates consecutive factory serials so two robots from
|
||||
/// The serial is burned into the chip and survives reflashes; it is the same value configd names
|
||||
/// the robot from, read where this board keeps a per-chip one ([`robotd_params::serial`]).
|
||||
/// `/etc/machine-id` (unique per OS install) is the fallback for a board without one. sha256 decorrelates consecutive factory serials so two robots from
|
||||
/// the same batch don't get neighbouring (and thus meaninglessly different) seeds.
|
||||
pub fn hardware_seed() -> Result<u32> {
|
||||
// **One machine, several ducks** — the one situation where deriving identity from hardware is
|
||||
@@ -138,15 +138,12 @@ pub fn hardware_seed() -> Result<u32> {
|
||||
if let Some(named) = std::env::var_os("DUCK_IDENTITY") {
|
||||
return Ok(seed_from_id(&named.to_string_lossy()));
|
||||
}
|
||||
let id = std::fs::read("/proc/device-tree/serial-number")
|
||||
.map(|raw| {
|
||||
String::from_utf8_lossy(&raw)
|
||||
.trim_matches(char::from(0))
|
||||
.trim()
|
||||
.to_owned()
|
||||
})
|
||||
.or_else(|_| std::fs::read_to_string("/etc/machine-id").map(|s| s.trim().to_owned()))
|
||||
.context("neither /proc/device-tree/serial-number nor /etc/machine-id is readable")?;
|
||||
let id = match robotd_params::serial::soc_serial() {
|
||||
Some(serial) => serial,
|
||||
None => std::fs::read_to_string("/etc/machine-id")
|
||||
.map(|s| s.trim().to_owned())
|
||||
.context("no SoC serial, and /etc/machine-id is not readable")?,
|
||||
};
|
||||
Ok(seed_from_id(&id))
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user