linked_devices/
link_devices.rs

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
use hdk::prelude::*;
use linked_devices_integrity::{
    AgentToLinkedDevicesLinkTag, LinkTypes, LinkedDevices, LinkedDevicesProof,
};

use crate::{utils::create_link_relaxed, Signal};

fn secret_from_passcode(passcode: Vec<u8>) -> CapSecret {
    let mut secret: CapSecretBytes = [0; CAP_SECRET_BYTES];

    for i in 0..passcode.len() {
        secret[i] = passcode[i];
    }

    for i in passcode.len()..(CAP_SECRET_BYTES - passcode.len()) {
        secret[i] = 0;
    }

    CapSecret::from(secret)
}

#[hdk_extern]
pub fn prepare_discover_agent() -> ExternResult<()> {
    let mut functions = BTreeSet::new();
    functions.insert((
        zome_info()?.name,
        FunctionName("receive_discover_agent".into()),
    ));
    let access = CapAccess::Unrestricted;
    let now = sys_time()?;
    let cap_grant_entry: CapGrantEntry = CapGrantEntry::new(
        format!("link-devices-{}", now), // A string by which to later query for saved grants.
        access,
        GrantedFunctions::Listed(functions),
    );

    create(CreateInput::new(
        EntryDefLocation::CapGrant,
        EntryVisibility::Private,
        Entry::CapGrant(cap_grant_entry),
        ChainTopOrdering::Relaxed,
    ))?;
    Ok(())
}

#[hdk_extern]
pub fn attempt_discover_agent(agent: AgentPubKey) -> ExternResult<()> {
    let response = call_remote(
        agent,
        zome_info()?.name,
        "receive_discover_agent".into(),
        None,
        (),
    )?;

    match response {
        ZomeCallResponse::Ok(_) => Ok(()),
        _ => Err(wasm_error!(WasmErrorInner::Guest(format!("{response:?}")))),
    }
}

#[hdk_extern]
pub fn receive_discover_agent() -> ExternResult<()> {
    let agent = call_info()?;
    emit_signal(Signal::AgentDiscovered {
        agent: agent.provenance,
    })?;
    Ok(())
}

#[derive(Serialize, Deserialize, Debug)]
pub struct PrepareLinkDevicesRequestorInput {
    pub recipient: AgentPubKey,
    pub my_passcode: Vec<u8>,
}
#[hdk_extern]
pub fn prepare_link_devices_requestor(input: PrepareLinkDevicesRequestorInput) -> ExternResult<()> {
    let mut functions = BTreeSet::new();
    functions.insert((
        zome_info()?.name,
        FunctionName("receive_accept_link_devices".into()),
    ));
    let access = CapAccess::Assigned {
        secret: secret_from_passcode(input.my_passcode),
        assignees: vec![input.recipient].into_iter().collect(),
    };
    let now = sys_time()?;
    let cap_grant_entry: CapGrantEntry = CapGrantEntry::new(
        format!("link-devices-{}", now), // A string by which to later query for saved grants.
        access,
        GrantedFunctions::Listed(functions),
    );

    create(CreateInput::new(
        EntryDefLocation::CapGrant,
        EntryVisibility::Private,
        Entry::CapGrant(cap_grant_entry),
        ChainTopOrdering::Relaxed,
    ))?;

    Ok(())
}

#[derive(Serialize, Deserialize, Debug)]
pub struct PrepareLinkDevicesRecipientInput {
    pub requestor: AgentPubKey,
    pub my_passcode: Vec<u8>,
}
#[hdk_extern]
pub fn prepare_link_devices_recipient(input: PrepareLinkDevicesRecipientInput) -> ExternResult<()> {
    let mut functions = BTreeSet::new();
    functions.insert((
        zome_info()?.name,
        FunctionName("receive_request_link_devices".into()),
    ));
    let access = CapAccess::Assigned {
        secret: secret_from_passcode(input.my_passcode),
        assignees: vec![input.requestor].into_iter().collect(),
    };
    let now = sys_time()?;
    let cap_grant_entry: CapGrantEntry = CapGrantEntry::new(
        format!("link-devices-{}", now), // A string by which to later query for saved grants.
        access,
        GrantedFunctions::Listed(functions),
    );

    create(CreateInput::new(
        EntryDefLocation::CapGrant,
        EntryVisibility::Private,
        Entry::CapGrant(cap_grant_entry),
        ChainTopOrdering::Relaxed,
    ))?;

    Ok(())
}

fn query_link_devices_cap_grants() -> ExternResult<Vec<Record>> {
    let filter = ChainQueryFilter::new()
        .entry_type(EntryType::CapGrant)
        .include_entries(true)
        .action_type(ActionType::Create);
    let records = query(filter)?;

    let mut link_agents_cap_grants = Vec::new();

    for record in records {
        let Some(entry) = record.entry().as_option() else {
            continue;
        };
        let Entry::CapGrant(cap_grant) = entry else {
            continue;
        };
        if cap_grant.tag.as_str().starts_with("link-devices-") {
            link_agents_cap_grants.push(record)
        }
    }

    Ok(link_agents_cap_grants)
}

#[hdk_extern]
pub fn clear_link_devices_cap_grants() -> ExternResult<()> {
    let link_agent_cap_grants = query_link_devices_cap_grants()?;

    for record in link_agent_cap_grants {
        delete(DeleteInput {
            deletes_action_hash: record.action_address().clone(),
            chain_top_ordering: ChainTopOrdering::Relaxed,
        })?;
    }

    Ok(())
}

#[derive(Serialize, Deserialize, Debug)]
pub struct RequestLinkDevicesInput {
    pub recipient: AgentPubKey,
    pub recipient_passcode: Vec<u8>,
}
#[hdk_extern]
pub fn request_link_devices(input: RequestLinkDevicesInput) -> ExternResult<()> {
    let response = call_remote(
        input.recipient,
        zome_info()?.name,
        "receive_request_link_devices".into(),
        Some(secret_from_passcode(input.recipient_passcode)),
        (),
    )?;

    match response {
        ZomeCallResponse::Ok(_) => Ok(()),
        _ => Err(wasm_error!(WasmErrorInner::Guest(format!("{response:?}")))),
    }
}

#[hdk_extern]
pub fn receive_request_link_devices() -> ExternResult<()> {
    let requestor = call_info()?.provenance;

    emit_signal(Signal::LinkDevicesInitialized { requestor })?;
    Ok(())
}

#[derive(Serialize, Deserialize, Debug)]
pub struct AcceptLinkDevicesInput {
    pub requestor: AgentPubKey,
    pub requestor_passcode: Vec<u8>,
}
// Called by the recipient
#[hdk_extern]
pub fn accept_link_devices(input: AcceptLinkDevicesInput) -> ExternResult<()> {
    let my_pub_key = agent_info()?.agent_initial_pubkey;

    let linked_devices = LinkedDevices {
        agents: vec![my_pub_key.clone(), input.requestor.clone()],
        timestamp: sys_time()?,
    };

    let my_signature = sign(my_pub_key.clone(), linked_devices.clone())?;
    let incomplete_proof = LinkedDevicesProof {
        linked_devices: linked_devices.clone(),
        signatures: vec![my_signature.clone()],
    };

    let response = call_remote(
        input.requestor.clone(),
        zome_info()?.name,
        "receive_accept_link_devices".into(),
        Some(secret_from_passcode(input.requestor_passcode)),
        incomplete_proof,
    )?;

    let ZomeCallResponse::Ok(result) = response else {
        clear_link_devices_cap_grants(())?;
        return Err(wasm_error!(WasmErrorInner::Guest(format!("{response:?}"))));
    };

    let signature: Signature = result.decode().map_err(|err| wasm_error!(err))?;

    let proof = LinkedDevicesProof {
        linked_devices,
        signatures: vec![my_signature, signature],
    };

    let tag = AgentToLinkedDevicesLinkTag(vec![proof]);

    create_link_devices_link(input.requestor, tag)?;

    clear_link_devices_cap_grants(())?;

    Ok(())
}

pub const LINKED_DEVICES_PROOF_TTL_US: u64 = 5_000_000; // 5 seconds

const TTL_LIVE_AGENTS_CAP_GRANTS: i64 = 1000 * 1000 * 60; // 1 minute

#[hdk_extern]
pub fn receive_accept_link_devices(
    incomplete_proof: LinkedDevicesProof,
) -> ExternResult<Signature> {
    let linked_devices = incomplete_proof.linked_devices;
    let my_pub_key = agent_info()?.agent_initial_pubkey;
    let call_info = call_info()?;
    let caller = call_info.provenance;

    if !linked_devices.agents.contains(&caller) {
        return Err(wasm_error!(WasmErrorInner::Guest(format!(
            "Caller is not in the LinkedDevicesProof"
        ))));
    }

    // If timestamp too big, error
    let now = sys_time()?;

    if now.as_micros() - linked_devices.timestamp.as_micros() > LINKED_DEVICES_PROOF_TTL_US as i64 {
        return Err(wasm_error!(WasmErrorInner::Guest(format!(
            "Timestamp is too old"
        ))));
    }

    let link_agents_cap_grants = query_link_devices_cap_grants()?;
    let now = sys_time()?;

    let recent_enough_cap_grant = link_agents_cap_grants.iter().find(|r| {
        now.as_micros() - r.action().timestamp().as_micros() < TTL_LIVE_AGENTS_CAP_GRANTS
    });

    let Some(_) = recent_enough_cap_grant else {
        clear_link_devices_cap_grants(())?;
        return Err(wasm_error!(WasmErrorInner::Guest(format!(
            "Timed out cap grant"
        ))));
    };

    let my_signature = sign(my_pub_key.clone(), linked_devices.clone())?;

    let proof = LinkedDevicesProof {
        linked_devices,
        signatures: vec![incomplete_proof.signatures[0].clone(), my_signature.clone()],
    };

    let tag = AgentToLinkedDevicesLinkTag(vec![proof]);

    create_link_devices_link(caller, tag)?;

    clear_link_devices_cap_grants(())?;

    Ok(my_signature)
}

pub fn create_link_devices_link(
    target_linked_device: AgentPubKey,
    tag: AgentToLinkedDevicesLinkTag,
) -> ExternResult<()> {
    let my_pub_key = agent_info()?.agent_initial_pubkey;

    let tag_bytes = SerializedBytes::try_from(tag).map_err(|err| wasm_error!(err))?;

    create_link_relaxed(
        my_pub_key,
        target_linked_device.clone(),
        LinkTypes::AgentToLinkedDevices,
        tag_bytes.bytes().clone(),
    )?;

    Ok(())
}