localharness 0.56.0

Agents that own themselves: one Rust crate that's both an agent SDK (streaming, tools, hooks, policies, triggers, MCP) and a wallet-owning, self-sovereign agent that runs in the browser.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
use k256::ecdsa::SigningKey;

use super::*;

// ─── Agent-teams P2P signaling (SignalingFacet) ────────────────────────────
// The on-chain seam for the WebRTC collaboration layer: a peer announces an
// EPHEMERAL signaling key under a TOPIC, discovers others via `peersOf`, then
// exchanges SDP offers/answers through `postSignal`/`inboxOf` (blobs sealed to
// the recipient's ephemeral pubkey). Topics:
//   - own devices: keccak256("localharness.devices" || owner_addr)
//   - agent team:  keccak256("localharness.team"   || team_id)
// `Presence` and `Signal` share the ABI shape `(address, uint64, bytes)`, so one
// decoder serves both reads.

/// Signaling topic for an owner's OWN devices.
pub fn devices_topic(owner_addr: &str) -> [u8; 32] {
    let mut pre = b"localharness.devices".to_vec();
    if let Ok(a) = parse_eth_address(owner_addr) {
        pre.extend_from_slice(&a);
    }
    keccak_key(&pre)
}

/// Signaling topic for an agent team.
pub fn team_topic(team_id: u64) -> [u8; 32] {
    let mut pre = b"localharness.team".to_vec();
    pre.extend_from_slice(&u256_be(team_id as u128));
    keccak_key(&pre)
}

/// 32-byte ABI word for an address (left-padded).
pub(crate) fn address_word(addr: &[u8; 20]) -> [u8; 32] {
    let mut w = [0u8; 32];
    w[12..32].copy_from_slice(addr);
    w
}

/// ABI-encode a trailing dynamic `bytes` (length word + padded data) onto `d`.
pub(crate) fn push_abi_bytes(d: &mut Vec<u8>, bytes: &[u8]) {
    d.extend_from_slice(&u256_be(bytes.len() as u128));
    d.extend_from_slice(bytes);
    let pad = (32 - (bytes.len() % 32)) % 32;
    d.extend(std::iter::repeat_n(0u8, pad));
}

/// The 32-byte digest the OWNER signs to authorize an `announce`:
/// `keccak256(topic || ephemeral || pubkey)` — `abi.encodePacked(bytes32,
/// address, bytes)` on-chain. MUST match `SignalingFacet.announce`'s digest
/// byte-for-byte (`topic[32] ‖ ephemeral_addr[20] ‖ raw pubkey`).
pub fn announce_digest(topic: &[u8; 32], ephemeral: &[u8; 20], pubkey: &[u8]) -> [u8; 32] {
    let mut pre = Vec::with_capacity(32 + 20 + pubkey.len());
    pre.extend_from_slice(topic);
    pre.extend_from_slice(ephemeral);
    pre.extend_from_slice(pubkey);
    keccak32(&pre)
}

/// The 32-byte digest a signer authorizes to evict `ephemeral` from `topic`:
/// `keccak256("localharness.leave" || topic || ephemeral)` —
/// `abi.encodePacked(string, bytes32, address)` on-chain. MUST match
/// `SignalingFacet.leave`'s digest byte-for-byte. The `"localharness.leave"`
/// prefix DOMAIN-SEPARATES it from `announce_digest` so an announce signature
/// can't be replayed as a leave.
pub fn leave_digest(topic: &[u8; 32], ephemeral: &[u8; 20]) -> [u8; 32] {
    let mut pre = Vec::with_capacity(18 + 32 + 20);
    pre.extend_from_slice(b"localharness.leave");
    pre.extend_from_slice(topic);
    pre.extend_from_slice(ephemeral);
    keccak32(&pre)
}

pub(crate) fn encode_leave(
    topic: &[u8; 32],
    owner: &[u8; 20],
    ephemeral: &[u8; 20],
    sig: &[u8; 65],
) -> Vec<u8> {
    // leave(bytes32 topic, address owner, address ephemeral, bytes sig).
    // Head: topic, owner, ephemeral, off(sig) = 4 words; one trailing `bytes`.
    let mut d = selector("leave(bytes32,address,address,bytes)").to_vec();
    d.extend_from_slice(topic);
    d.extend_from_slice(&address_word(owner));
    d.extend_from_slice(&address_word(ephemeral));
    d.extend_from_slice(&u256_be(0x80)); // offset to `sig` (4 head words in)
    push_abi_bytes(&mut d, sig);
    d
}

/// Leave `topic`'s roster (sponsored; tx caller = `sender`/master), evicting
/// `ephemeral`. For a DEVICES topic the digest
/// `keccak256("localharness.leave"||topic||ephemeral)` is signed with `owner_key`
/// (the seed holder, recovered against `owner` on-chain). Only the seed holder
/// can edit the roster — mirrors `announce_sponsored`.
pub async fn leave_sponsored(
    sender: &SigningKey,
    fee_payer: &SigningKey,
    owner_key: &SigningKey,
    owner: &[u8; 20],
    topic: &[u8; 32],
    ephemeral: &[u8; 20],
    fee_token: &str,
) -> Result<String, String> {
    let digest = leave_digest(topic, ephemeral);
    let sig = crate::wallet::sign_hash(owner_key, &digest); // low-s r‖s‖v, v∈{27,28}
    sponsored_diamond_call(
        sender,
        fee_payer,
        encode_leave(topic, owner, ephemeral, &sig),
        fee_token,
        1_200_000,
    )
    .await
}

pub(crate) fn encode_announce(
    topic: &[u8; 32],
    owner: &[u8; 20],
    ephemeral: &[u8; 20],
    pubkey: &[u8],
    sig: &[u8; 65],
) -> Vec<u8> {
    // announce(bytes32 topic, address owner, address ephemeral, bytes pubkey,
    //          bytes sig). Head: topic, owner, ephemeral, off(pubkey), off(sig)
    // = 5 words. Two trailing dynamic `bytes` (pubkey then sig).
    let mut d = selector("announce(bytes32,address,address,bytes,bytes)").to_vec();
    d.extend_from_slice(topic);
    d.extend_from_slice(&address_word(owner));
    d.extend_from_slice(&address_word(ephemeral));
    // 5 head words = 0xa0 bytes before the first dynamic payload.
    d.extend_from_slice(&u256_be(0xa0)); // offset to `pubkey`
    // pubkey tail = len word + padded data; sig follows it.
    let pubkey_tail = 32 + pubkey.len().div_ceil(32) * 32;
    d.extend_from_slice(&u256_be((0xa0 + pubkey_tail) as u128)); // offset to `sig`
    push_abi_bytes(&mut d, pubkey);
    push_abi_bytes(&mut d, sig);
    d
}

/// Announce `ephemeral` + `pubkey` under `topic` (sponsored; tx caller =
/// `sender`/master). `owner` is the seed-holder whose key authorizes the
/// announcement; the digest `keccak256(topic||ephemeral||pubkey)` is signed
/// with `owner_key` (the same seed key — `sender` and `owner_key` are the same
/// wallet on the owner's device). The facet recovers the sig vs `owner` and
/// requires `topic == devices_topic(owner)`, so an attacker without the seed
/// can't populate the roster.
#[allow(clippy::too_many_arguments)]
pub async fn announce_sponsored(
    sender: &SigningKey,
    fee_payer: &SigningKey,
    owner_key: &SigningKey,
    owner: &[u8; 20],
    topic: &[u8; 32],
    ephemeral: &[u8; 20],
    pubkey: &[u8],
    fee_token: &str,
) -> Result<String, String> {
    let digest = announce_digest(topic, ephemeral, pubkey);
    let sig = crate::wallet::sign_hash(owner_key, &digest); // low-s r‖s‖v, v∈{27,28}
    let gas = 1_200_000u128 + (pubkey.len() as u128) * 9_000;
    sponsored_diamond_call(
        sender,
        fee_payer,
        encode_announce(topic, owner, ephemeral, pubkey, &sig),
        fee_token,
        gas,
    )
    .await
}

pub(crate) fn encode_post_signal(to: &[u8; 20], blob: &[u8]) -> Vec<u8> {
    let mut d = selector("postSignal(address,bytes)").to_vec();
    d.extend_from_slice(&address_word(to));
    d.extend_from_slice(&u256_be(0x40)); // offset to `blob` (2 head words in)
    push_abi_bytes(&mut d, blob);
    d
}

/// Post a signaling blob (an SDP offer/answer/ICE bundle, sealed to `to`) into
/// `to`'s inbox (sponsored).
pub async fn post_signal_sponsored(
    sender: &SigningKey,
    fee_payer: &SigningKey,
    to: &[u8; 20],
    blob: &[u8],
    fee_token: &str,
) -> Result<String, String> {
    let gas = 1_200_000u128 + (blob.len() as u128) * 9_000;
    sponsored_diamond_call(sender, fee_payer, encode_post_signal(to, blob), fee_token, gas).await
}

/// One discovered/received entry. `peersOf` → (ephemeral, ts, pubkey);
/// `inboxOf` → (from, ts, blob).
pub type AddrTsBytes = (String, u64, Vec<u8>);

/// Decode an ABI `(address, uint64, bytes)[]` return — the shared shape of
/// `Presence[]` (peersOf) and `Signal[]` (inboxOf). Bounds-checked: a malformed
/// word stops decoding rather than panicking.
pub(crate) fn decode_addr_ts_bytes_array(result_hex: &str) -> Vec<AddrTsBytes> {
    let raw = match hex_to_bytes(result_hex) {
        Ok(b) => b,
        Err(_) => return Vec::new(),
    };
    // `read_usize` reads the low 8 bytes of a 32-byte word — so any offset or
    // length is an attacker-controlled value up to u64::MAX. Every derived index
    // below uses checked arithmetic so a hostile word stops the decode (returns
    // what was parsed so far) instead of overflowing (panic in debug / wraparound
    // garbage in release) or slicing out of bounds.
    let read_usize = |off: usize| -> Option<usize> {
        let end = off.checked_add(32)?;
        let w = raw.get(off..end)?;
        Some(u64::from_be_bytes(w[24..32].try_into().ok()?) as usize)
    };
    let mut out = Vec::new();
    let arr_off = match read_usize(0) {
        Some(o) => o,
        None => return out,
    };
    let len = match read_usize(arr_off) {
        Some(l) => l,
        None => return out,
    };
    let heads = match arr_off.checked_add(32) {
        Some(h) => h, // element offsets are relative to here
        None => return out,
    };
    for i in 0..len {
        // head slot for element i = heads + i*32
        let head_slot = match i.checked_mul(32).and_then(|o| heads.checked_add(o)) {
            Some(s) => s,
            None => break,
        };
        let elem = match read_usize(head_slot) {
            Some(rel) => match heads.checked_add(rel) {
                Some(e) => e,
                None => break,
            },
            None => break,
        };
        let addr = match elem
            .checked_add(12)
            .zip(elem.checked_add(32))
            .and_then(|(a, b)| raw.get(a..b))
        {
            Some(a) => format!("0x{}", bytes_to_hex(a)),
            None => break,
        };
        let ts = match elem
            .checked_add(56)
            .zip(elem.checked_add(64))
            .and_then(|(a, b)| raw.get(a..b))
        {
            Some(t) => u64::from_be_bytes(t.try_into().unwrap_or_default()),
            None => break,
        };
        let boff = match elem.checked_add(64).and_then(read_usize) {
            // bytes offset is relative to the element
            Some(rel) => match elem.checked_add(rel) {
                Some(b) => b,
                None => break,
            },
            None => break,
        };
        let blen = match read_usize(boff) {
            Some(l) => l,
            None => break,
        };
        let bytes = boff
            .checked_add(32)
            .and_then(|start| start.checked_add(blen).map(|end| (start, end)))
            .and_then(|(start, end)| raw.get(start..end))
            .map(|s| s.to_vec())
            .unwrap_or_default();
        out.push((addr, ts, bytes));
    }
    out
}

/// The ephemeral peers announced under `topic` (peersOf). Callers filter stale
/// entries by the `ts` field.
pub async fn peers_of(topic: &[u8; 32]) -> Result<Vec<AddrTsBytes>, String> {
    let res = read_view(selector("peersOf(bytes32)"), &[*topic]).await?;
    Ok(decode_addr_ts_bytes_array(&res))
}

/// `peer`'s signaling inbox from `from_index` onward (inboxOf). The caller
/// tracks its own cursor.
pub async fn inbox_of(peer: &[u8; 20], from_index: u64) -> Result<Vec<AddrTsBytes>, String> {
    let res = read_view(
        selector("inboxOf(address,uint256)"),
        &[address_word(peer), u256_be(from_index as u128)],
    )
    .await?;
    Ok(decode_addr_ts_bytes_array(&res))
}

/// `peer`'s inbox length (a cheap cursor poll).
pub async fn inbox_length(peer: &[u8; 20]) -> Result<u64, String> {
    let res = read_view(selector("inboxLength(address)"), &[address_word(peer)]).await?;
    let raw = hex_to_bytes(&res)?;
    if raw.len() < 32 {
        return Ok(0);
    }
    Ok(u64::from_be_bytes(raw[24..32].try_into().map_err(|_| "bad len")?))
}

// ─── OFF-CHAIN signaling relay (proxy `/api/signal`) ────────────────────────
// The cheap matchmaking path for ARBITRARY cross-owner WebRTC rooms (multiplayer):
// peers exchange SDP via the proxy's GitHub-backed relay instead of sponsored
// on-chain announce/postSignal (each ~1.2M gas — the pattern the scheduler moved
// off-chain to escape). The on-chain SignalingFacet above stays for the trustless
// same-owner device-sync path. webrtc.rs uses NON-TRICKLE ICE, so one SDP blob per
// side ("offer"/"answer") completes a pairing; the data then flows P2P.

/// POST this side's SDP blob to the relay under `room`/`slot` (personal-sign
/// authed; anti-spam). `slot` is `"offer"` or `"answer"`. `now_secs` is passed in
/// so this is cross-target (CLI `SystemTime` / browser `js_sys::Date::now()`).
pub async fn signal_post(
    signer: &SigningKey,
    now_secs: u64,
    room: &str,
    slot: &str,
    sdp: &str,
) -> Result<(), String> {
    let token = proxy_auth_token(signer, now_secs);
    let url = format!("{CREDIT_PROXY_URL}api/signal");
    let body = serde_json::json!({ "room": room, "slot": slot, "sdp": sdp });
    http_post_json_authed(&url, &token, &body).await
}

/// Poll the relay for a peer's SDP blob at `room`/`slot` (open GET — the room id
/// is the capability). `Ok(None)` = not posted yet, or stale (past the relay TTL).
pub async fn signal_get(room: &str, slot: &str) -> Result<Option<String>, String> {
    let url = format!("{CREDIT_PROXY_URL}api/signal?room={room}&slot={slot}");
    match http_get_bytes(&url).await? {
        Some(bytes) => {
            let v: serde_json::Value =
                serde_json::from_slice(&bytes).map_err(|e| format!("signal_get: bad json: {e}"))?;
            Ok(v.get("sdp").and_then(|s| s.as_str()).map(String::from))
        }
        None => Ok(None),
    }
}

/// Clear a room's slots once the peers have connected (best-effort cleanup;
/// personal-sign authed).
pub async fn signal_clear(signer: &SigningKey, now_secs: u64, room: &str) -> Result<(), String> {
    let token = proxy_auth_token(signer, now_secs);
    let url = format!("{CREDIT_PROXY_URL}api/signal");
    let body = serde_json::json!({ "action": "clear", "room": room });
    http_post_json_authed(&url, &token, &body).await
}

/// N-PEER STAR: append this joiner's id to the room's roster so the HOST (which
/// can't list per-joiner slots in the store) discovers it. Personal-sign authed.
pub async fn signal_join(
    signer: &SigningKey,
    now_secs: u64,
    room: &str,
    joiner_id: &str,
) -> Result<(), String> {
    let token = proxy_auth_token(signer, now_secs);
    let url = format!("{CREDIT_PROXY_URL}api/signal");
    let body = serde_json::json!({ "action": "join", "room": room, "joiner": joiner_id });
    http_post_json_authed(&url, &token, &body).await
}

/// N-PEER STAR: poll the room's roster for joiner ids (open GET — the host calls
/// this each tick). `Ok(vec![])` if no roster yet or it's past the relay TTL.
pub async fn signal_get_joiners(room: &str) -> Result<Vec<String>, String> {
    let url = format!("{CREDIT_PROXY_URL}api/signal?room={room}&slot=join");
    match http_get_bytes(&url).await? {
        Some(bytes) => {
            let v: serde_json::Value = serde_json::from_slice(&bytes)
                .map_err(|e| format!("signal_get_joiners: bad json: {e}"))?;
            Ok(v.get("joiners")
                .and_then(|j| j.as_array())
                .map(|a| a.iter().filter_map(|x| x.as_str().map(String::from)).collect())
                .unwrap_or_default())
        }
        None => Ok(Vec::new()),
    }
}

// ─── MESH membership (proxy `/api/signal` `slots` blob) ──────────────────────
// The HOSTLESS-mesh roster: a fixed 8-slot blob where each peer OWNS one slot
// {id, addr, ts}. The SERVER stamps `ts` (skew-free freshness) and returns its
// `now` on every read; a stale slot (now - ts > a window) is reclaimable. CAS-
// guarded by the blob `sha` so concurrent claims/heartbeats serialize.

/// Mesh capacity (mirrors the worker's MP_PEERS + signal.ts MESH_SLOTS).
pub const MESH_SLOTS: usize = 8;

/// One mesh membership slot: a peer's short id, full address (the anti-spoof key
/// — only the address owner may write its slot), and the server-stamped ts.
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct SlotEntry {
    pub id: String,
    pub addr: String,
    pub ts: u64,
}

/// The mesh slots blob + the SERVER `now` (freshness anchor) + the blob `sha`
/// (for the next CAS write). `slots` is always length [`MESH_SLOTS`].
pub struct MeshSlots {
    pub slots: Vec<Option<SlotEntry>>,
    pub now: u64,
    pub sha: Option<String>,
}

/// Read the mesh `slots` blob (open GET). Returns 8 slots (Nones if empty/new),
/// the server `now`, and the blob sha.
pub async fn signal_get_slots(room: &str) -> Result<MeshSlots, String> {
    let url = format!("{CREDIT_PROXY_URL}api/signal?room={room}&slot=slots");
    let mut slots: Vec<Option<SlotEntry>> = vec![None; MESH_SLOTS];
    let mut now: u64 = 0;
    let mut sha: Option<String> = None;
    if let Some(bytes) = http_get_bytes(&url).await? {
        let v: serde_json::Value =
            serde_json::from_slice(&bytes).map_err(|e| format!("get_slots: bad json: {e}"))?;
        now = v.get("now").and_then(|x| x.as_u64()).unwrap_or(0);
        sha = v.get("sha").and_then(|x| x.as_str()).map(String::from);
        if let Some(arr) = v.get("slots").and_then(|s| s.as_array()) {
            for (i, e) in arr.iter().take(MESH_SLOTS).enumerate() {
                slots[i] = serde_json::from_value::<SlotEntry>(e.clone()).ok();
            }
        }
    }
    Ok(MeshSlots { slots, now, sha })
}

/// Outcome of a CAS `put-slots`: written, or a sha conflict (re-read + retry).
pub enum PutSlots {
    Written,
    Conflict,
}

/// Write the mesh slots blob under a CAS sha guard. `slots[my_idx]` MUST carry
/// the signer's own address (the server enforces it and stamps the entry's ts).
/// `Conflict` = another peer wrote first; the caller re-reads + retries.
pub async fn signal_put_slots(
    signer: &SigningKey,
    now_secs: u64,
    room: &str,
    slots: &[Option<SlotEntry>],
    my_idx: usize,
    sha: Option<&str>,
) -> Result<PutSlots, String> {
    let token = proxy_auth_token(signer, now_secs);
    let url = format!("{CREDIT_PROXY_URL}api/signal");
    let body = serde_json::json!({
        "action": "put-slots",
        "room": room,
        "slots": slots,
        "my": my_idx,
        "sha": sha.unwrap_or(""),
    });
    let (code, _v) = http_post_json_authed_with_status(&url, &token, &body).await?;
    match code {
        200 => Ok(PutSlots::Written),
        409 => Ok(PutSlots::Conflict),
        c => Err(format!("put-slots: HTTP {c}")),
    }
}

/// Fetch the proxy's WebRTC ICE-server config JSON (`{iceServers:[…]}`) — STUN
/// always, TURN when the proxy is provisioned (`/api/turn`). Open GET. The browser
/// parses it into the RtcConfiguration. Returns the raw JSON body text.
pub async fn fetch_ice_json() -> Result<String, String> {
    let url = format!("{CREDIT_PROXY_URL}api/turn");
    match http_get_bytes(&url).await? {
        Some(b) => String::from_utf8(b).map_err(|e| format!("ice json: {e}")),
        None => Err("ice config unavailable".to_string()),
    }
}

// ─── Open chatroom relay (proxy `/api/chat`) ────────────────────────────────
// Per-room append-only text log (room = the cartridge's subdomain). POST a
// message (personal-sign authed); poll the log (open GET). Backs `host::chat`.

/// Post a chat message to `room` (personal-sign authed; the relay stamps the
/// sender's short address as the display name). `Ok(())` on success.
pub async fn chat_post(signer: &SigningKey, now_secs: u64, room: &str, text: &str) -> Result<(), String> {
    let token = proxy_auth_token(signer, now_secs);
    let url = format!("{CREDIT_PROXY_URL}api/chat");
    let body = serde_json::json!({ "room": room, "text": text });
    http_post_json_authed(&url, &token, &body).await
}

/// Poll `room`'s log for messages with `n > after` (open GET). Returns
/// `(n, name, text)` tuples, oldest-first.
pub async fn chat_poll(room: &str, after: i64) -> Result<Vec<(i64, String, String)>, String> {
    let url = format!("{CREDIT_PROXY_URL}api/chat?room={room}&after={after}");
    let bytes = match http_get_bytes(&url).await? {
        Some(b) => b,
        None => return Ok(Vec::new()),
    };
    let v: serde_json::Value =
        serde_json::from_slice(&bytes).map_err(|e| format!("chat poll: bad json: {e}"))?;
    let mut out = Vec::new();
    if let Some(msgs) = v.get("messages").and_then(|m| m.as_array()) {
        for m in msgs {
            let n = m.get("n").and_then(|x| x.as_i64()).unwrap_or(0);
            let name = m.get("name").and_then(|x| x.as_str()).unwrap_or("?").to_string();
            let text = m.get("text").and_then(|x| x.as_str()).unwrap_or("").to_string();
            out.push((n, name, text));
        }
    }
    Ok(out)
}


#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn decode_presence_signal_array() {
        // Hand-crafted ABI `(address, uint64, bytes)[]` with one element:
        // (0x11..11, ts=5, bytes=[0xAA, 0xBB]) — the Presence/Signal shape that
        // peersOf/inboxOf return. Verifies the nested-offset decode.
        let hex = String::from("0x")
            + "0000000000000000000000000000000000000000000000000000000000000020" // array offset
            + "0000000000000000000000000000000000000000000000000000000000000001" // len = 1
            + "0000000000000000000000000000000000000000000000000000000000000020" // head[0] offset
            + "0000000000000000000000001111111111111111111111111111111111111111" // address
            + "0000000000000000000000000000000000000000000000000000000000000005" // ts = 5
            + "0000000000000000000000000000000000000000000000000000000000000060" // bytes offset
            + "0000000000000000000000000000000000000000000000000000000000000002" // bytes len = 2
            + "aabb000000000000000000000000000000000000000000000000000000000000"; // bytes data
        let out = decode_addr_ts_bytes_array(&hex);
        assert_eq!(out.len(), 1);
        assert_eq!(out[0].0, "0x1111111111111111111111111111111111111111");
        assert_eq!(out[0].1, 5);
        assert_eq!(out[0].2, vec![0xAA, 0xBB]);
        // An empty array decodes to nothing (no panic).
        let empty = String::from("0x")
            + "0000000000000000000000000000000000000000000000000000000000000020"
            + "0000000000000000000000000000000000000000000000000000000000000000";
        assert!(decode_addr_ts_bytes_array(&empty).is_empty());
    }

    #[test]
    fn devices_topic_preimage_is_label_then_raw_address() {
        // MUST equal keccak256("localharness.devices" || owner_20bytes), the
        // SAME preimage SignalingFacet recomputes on-chain as
        // keccak256(abi.encodePacked("localharness.devices", owner)). Any drift
        // here silently breaks the owner-gated announce (topic != devicesTopic).
        let owner = "0x1111111111111111111111111111111111111111";
        let topic = devices_topic(owner);
        let mut pre = b"localharness.devices".to_vec();
        pre.extend_from_slice(&parse_eth_address(owner).unwrap());
        assert_eq!(topic, keccak_key(&pre));
        // The label is 20 ASCII bytes; the address is appended raw (20 bytes),
        // so the preimage is exactly 40 bytes.
        assert_eq!(pre.len(), 40);
    }

    #[test]
    fn announce_digest_is_packed_topic_ephemeral_pubkey() {
        // The owner signs keccak256(topic || ephemeral || pubkey) — matching
        // SignalingFacet's keccak256(abi.encodePacked(bytes32, address, bytes)).
        // topic[32] ‖ ephemeral_addr[20] ‖ raw pubkey, NO padding.
        let topic = [0xABu8; 32];
        let eph = [0x22u8; 20];
        let pubkey = vec![0x02u8; 33];
        let mut pre = Vec::new();
        pre.extend_from_slice(&topic);
        pre.extend_from_slice(&eph);
        pre.extend_from_slice(&pubkey);
        assert_eq!(pre.len(), 32 + 20 + 33);
        assert_eq!(announce_digest(&topic, &eph, &pubkey), keccak32(&pre));
    }

    #[test]
    fn leave_digest_is_prefixed_packed_topic_ephemeral() {
        // The signer authorizes keccak256("localharness.leave" || topic ||
        // ephemeral) — matching SignalingFacet.leave's
        // keccak256(abi.encodePacked(string, bytes32, address)). The prefix
        // DOMAIN-SEPARATES it from the announce digest (no prefix), so the two
        // must differ for the same topic/ephemeral.
        let topic = [0xABu8; 32];
        let eph = [0x22u8; 20];
        let mut pre = b"localharness.leave".to_vec();
        pre.extend_from_slice(&topic);
        pre.extend_from_slice(&eph);
        assert_eq!(pre.len(), 18 + 32 + 20);
        assert_eq!(leave_digest(&topic, &eph), keccak32(&pre));
        // Domain separation: a leave digest must NOT equal an announce digest
        // (else an announce sig could be replayed as a leave).
        let pubkey = vec![0x02u8; 33];
        assert_ne!(leave_digest(&topic, &eph), announce_digest(&topic, &eph, &pubkey));
    }

    #[test]
    fn encode_leave_4arg_layout() {
        // Pin the selector + the single-trailing-bytes ABI layout so it matches
        // leave(bytes32,address,address,bytes).
        let topic = [0x11u8; 32];
        let owner = [0x22u8; 20];
        let eph = [0x33u8; 20];
        let sig = [0x44u8; 65];
        let cd = encode_leave(&topic, &owner, &eph, &sig);

        assert_eq!(&cd[..4], &selector("leave(bytes32,address,address,bytes)"));
        // Head: topic, owner, ephemeral, off(sig)=0x80 (4 head words).
        assert_eq!(&cd[4..36], &topic[..]);
        assert_eq!(&cd[36..68], &address_word(&owner)[..]);
        assert_eq!(&cd[68..100], &address_word(&eph)[..]);
        assert_eq!(&cd[100..132], &u256_be(0x80)[..]); // sig offset
        // sig tail at 4 + 0x80 = 0x84: len word (65) then 96 padded bytes.
        let sig_off = 4 + 0x80;
        assert_eq!(&cd[sig_off..sig_off + 32], &u256_be(65)[..]);
        assert_eq!(&cd[sig_off + 32..sig_off + 32 + 65], &sig[..]);
        // Total: 4 sel + 4 head words + (32+96) sig.
        assert_eq!(cd.len(), 4 + 4 * 32 + (32 + 96));
    }

    #[test]
    fn leave_digest_signature_recovers_to_owner() {
        // The sig the driver attaches for a devices-topic leave MUST recover to
        // the OWNER over the leave digest — exactly what the facet's `_recover`
        // checks (`recover(...) == owner`).
        let w = crate::wallet::generate();
        let owner = crate::wallet::address(&w.signer); // [u8;20]
        let topic = [0x11u8; 32];
        let eph = [0x99u8; 20];
        let digest = leave_digest(&topic, &eph);
        let sig = crate::wallet::sign_hash(&w.signer, &digest); // low-s r‖s‖v
        let recovered = crate::wallet::recover_address(&sig, &digest)
            .expect("sig recovers");
        assert_eq!(recovered, owner, "leave sig recovers to the owner");
    }

    #[test]
    fn announce_digest_signature_recovers_to_owner() {
        // Full round-trip: the sig the driver attaches MUST recover to the
        // OWNER over the announce digest — exactly what the facet's `_recover`
        // checks (`recover(...) == owner`). Proves the driver's signing path
        // and the facet's recovery path agree.
        let w = crate::wallet::generate();
        let owner = crate::wallet::address(&w.signer); // [u8;20]
        let topic = [0x11u8; 32];
        let eph = [0x99u8; 20];
        let pubkey = vec![0x03u8; 33];
        let digest = announce_digest(&topic, &eph, &pubkey);
        let sig = crate::wallet::sign_hash(&w.signer, &digest); // low-s r‖s‖v
        let recovered = crate::wallet::recover_address(&sig, &digest)
            .expect("sig recovers");
        assert_eq!(recovered, owner, "announce sig recovers to the owner");
    }

    #[test]
    fn encode_announce_5arg_layout() {
        // New owner-signed signature; pin the selector + the two-trailing-bytes
        // ABI layout so it matches announce(bytes32,address,address,bytes,bytes).
        let topic = [0x11u8; 32];
        let owner = [0x22u8; 20];
        let eph = [0x33u8; 20];
        let pubkey = vec![0x02u8; 33]; // compressed-pubkey-shaped (1 padded word past len)
        let sig = [0x44u8; 65];
        let cd = encode_announce(&topic, &owner, &eph, &pubkey, &sig);

        assert_eq!(
            &cd[..4],
            &selector("announce(bytes32,address,address,bytes,bytes)")
        );
        // Head: topic, owner, ephemeral, off(pubkey)=0xa0, off(sig)=0xa0+96=0x100.
        assert_eq!(&cd[4..36], &topic[..]);
        assert_eq!(&cd[36..68], &address_word(&owner)[..]);
        assert_eq!(&cd[68..100], &address_word(&eph)[..]);
        assert_eq!(&cd[100..132], &u256_be(0xa0)[..]); // pubkey offset
        assert_eq!(&cd[132..164], &u256_be(0x100)[..]); // sig offset (0xa0 + 0x60)
        // pubkey tail at 4 + 0xa0 = 0xa4: len word (33) then 64 padded bytes.
        let pk_off = 4 + 0xa0;
        assert_eq!(&cd[pk_off..pk_off + 32], &u256_be(33)[..]);
        assert_eq!(&cd[pk_off + 32..pk_off + 32 + 33], &pubkey[..]);
        // sig tail at 4 + 0x100 = 0x104: len word (65) then 96 padded bytes.
        let sig_off = 4 + 0x100;
        assert_eq!(&cd[sig_off..sig_off + 32], &u256_be(65)[..]);
        assert_eq!(&cd[sig_off + 32..sig_off + 32 + 65], &sig[..]);
        // Total: 4 sel + 5 head words + (32+64) pubkey + (32+96) sig.
        assert_eq!(cd.len(), 4 + 5 * 32 + (32 + 64) + (32 + 96));
    }

    #[test]
    fn addr_ts_bytes_array_empty_and_short_inputs() {
        // Totally empty RPC result ("0x").
        assert!(decode_addr_ts_bytes_array("0x").is_empty());
        // Not even one word.
        assert!(decode_addr_ts_bytes_array("0x00").is_empty());
        // Odd-length / non-hex never panics (hex_to_bytes errors → empty).
        assert!(decode_addr_ts_bytes_array("0xabc").is_empty());
        assert!(decode_addr_ts_bytes_array("0xzz").is_empty());
        assert!(decode_addr_ts_bytes_array("nonsense").is_empty());
        // Array offset points past the buffer → empty, no panic.
        let off_oob = format!("0x{}", word_usize(0x40)); // offset 64, only 32 bytes present
        assert!(decode_addr_ts_bytes_array(&off_oob).is_empty());
    }

    #[test]
    fn addr_ts_bytes_array_hostile_offsets_dont_overflow() {
        // Array offset = u64::MAX. `arr_off + 32` must NOT overflow.
        let huge_off = format!("0x{}", word_u64_max());
        assert!(decode_addr_ts_bytes_array(&huge_off).is_empty());

        // Valid array offset (0x20) + length = u64::MAX. The per-element head
        // read must stop at the buffer end, not loop u64::MAX times or overflow
        // `heads + i*32`.
        let huge_len = format!("0x{}{}", word_usize(0x20), word_u64_max());
        assert!(decode_addr_ts_bytes_array(&huge_len).is_empty());

        // One element whose head-offset word is u64::MAX → `heads + rel` overflow.
        let bad_head = String::from("0x")
            + &word_usize(0x20) // array offset
            + &word_usize(1) // len = 1
            + &word_u64_max(); // head[0] = u64::MAX (relative element offset)
        assert!(decode_addr_ts_bytes_array(&bad_head).is_empty());

        // One element whose inner bytes-offset is u64::MAX → `elem + rel` overflow.
        let bad_bytes_off = String::from("0x")
            + &word_usize(0x20) // array offset
            + &word_usize(1) // len = 1
            + &word_usize(0x20) // head[0] → element starts right after heads
            + &word_usize(0x1111) // address word
            + &word_usize(7) // ts
            + &word_u64_max(); // bytes offset = u64::MAX
        assert!(decode_addr_ts_bytes_array(&bad_bytes_off).is_empty());
    }

    #[test]
    fn addr_ts_bytes_array_multi_element_decodes() {
        // Two elements: (0x11..,1,[0xAA]) and (0x22..,2,[0xBB,0xCC]).
        // Each element is a `(address,uint64,bytes)` tuple, encoded as 5 words:
        // [addr][ts][bytes-rel-offset(0x60)][bytes-len][bytes-data].
        let elem0 = String::from("")
            + "0000000000000000000000001111111111111111111111111111111111111111" // addr
            + &word_usize(1) // ts
            + &word_usize(0x60) // bytes offset (relative to element)
            + &word_usize(1) // bytes len
            + "aa00000000000000000000000000000000000000000000000000000000000000"; // data
        let elem1 = String::from("")
            + "0000000000000000000000002222222222222222222222222222222222222222"
            + &word_usize(2)
            + &word_usize(0x60)
            + &word_usize(2)
            + "bbcc000000000000000000000000000000000000000000000000000000000000";
        // elem0 is 5 words = 0xA0 bytes. heads = arr_off(0x20)+0x20 = 0x40.
        // head[0] rel = 0x40 (2 head words), head[1] rel = 0x40 + 0xA0 = 0xE0.
        let hex = String::from("0x")
            + &word_usize(0x20) // array offset
            + &word_usize(2) // len = 2
            + &word_usize(0x40) // head[0]
            + &word_usize(0xE0) // head[1]
            + &elem0
            + &elem1;
        let out = decode_addr_ts_bytes_array(&hex);
        assert_eq!(out.len(), 2);
        assert_eq!(out[0].0, "0x1111111111111111111111111111111111111111");
        assert_eq!(out[0].1, 1);
        assert_eq!(out[0].2, vec![0xAA]);
        assert_eq!(out[1].0, "0x2222222222222222222222222222222222222222");
        assert_eq!(out[1].1, 2);
        assert_eq!(out[1].2, vec![0xBB, 0xCC]);
    }
}