pub fn weigh_placeholder() -> EntryRateWeight
Expand description

Placeholder for weighing. Currently produces zero weight.

Examples found in repository?
src/core/workflow/countersigning_workflow.rs (line 72)
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
pub(crate) fn incoming_countersigning(
    ops: Vec<(DhtOpHash, DhtOp)>,
    workspace: &CountersigningWorkspace,
    trigger: TriggerSender,
) -> WorkflowResult<()> {
    let mut should_trigger = false;

    // For each op check it's the right type and extract the
    // entry hash, required actions and expires time.
    for (hash, op) in ops {
        // Must be a store entry op.
        if let DhtOp::StoreEntry(_, _, entry) = &op {
            // Must have a counter sign entry type.
            if let Entry::CounterSign(session_data, _) = entry.as_ref() {
                let entry_hash = EntryHash::with_data_sync(&**entry);
                // Get the required actions for this session.
                let weight = weigh_placeholder();
                let action_set = session_data.build_action_set(entry_hash, weight)?;

                // Get the expires time for this session.
                let expires = *session_data.preflight_request().session_times.end();

                // Get the entry hash from an action.
                // If the actions have different entry hashes they will fail validation.
                if let Some(entry_hash) = action_set.first().and_then(|h| h.entry_hash().cloned()) {
                    // Hash the required actions.
                    let required_actions: Vec<_> = action_set
                        .into_iter()
                        .map(|h| ActionHash::with_data_sync(&h))
                        .collect();

                    // Check if already timed out.
                    if holochain_zome_types::Timestamp::now() < expires {
                        // Put this op in the pending map.
                        workspace.put(entry_hash, hash, op, required_actions, expires);
                        // We have new ops so we should trigger the workflow.
                        should_trigger = true;
                    }
                }
            }
        }
    }

    // Trigger the workflow if we have new ops.
    if should_trigger {
        trigger.trigger(&"incoming_countersigning");
    }
    Ok(())
}

/// Countersigning workflow that checks for complete sessions and
/// pushes the complete ops to validation then messages the signers.
pub(crate) async fn countersigning_workflow(
    space: &Space,
    network: &(dyn HolochainP2pDnaT + Send + Sync),
    sys_validation_trigger: &TriggerSender,
) -> WorkflowResult<WorkComplete> {
    // Get any complete sessions.
    let complete_sessions = space.countersigning_workspace.get_complete_sessions();
    let mut notify_agents = Vec::with_capacity(complete_sessions.len());

    // For each complete session send the ops to validation.
    for (agents, ops, actions) in complete_sessions {
        let non_enzymatic_ops: Vec<_> = ops
            .into_iter()
            .filter(|(_hash, dht_op)| dht_op.enzymatic_countersigning_enzyme().is_none())
            .collect();
        if !non_enzymatic_ops.is_empty() {
            incoming_dht_ops_workflow(
                space,
                sys_validation_trigger.clone(),
                non_enzymatic_ops,
                false,
            )
            .await?;
        }
        notify_agents.push((agents, actions));
    }

    // For each complete session notify the agents of success.
    for (agents, actions) in notify_agents {
        if let Err(e) = network
            .countersigning_session_negotiation(
                agents,
                CountersigningSessionNegotiationMessage::AuthorityResponse(actions),
            )
            .await
        {
            // This could likely fail if a signer is offline so it's not really an error.
            tracing::info!(
                "Failed to notify agents: counter signed actions because of {:?}",
                e
            );
        }
    }
    Ok(WorkComplete::Complete)
}

/// An incoming countersigning session success.
pub(crate) async fn countersigning_success(
    space: Space,
    network: &HolochainP2pDna,
    author: AgentPubKey,
    signed_actions: Vec<SignedAction>,
    trigger: QueueTriggers,
    mut signal: SignalBroadcaster,
) -> WorkflowResult<()> {
    let authored_db = space.authored_db;
    let dht_db = space.dht_db;
    let dht_db_cache = space.dht_query_cache;
    let QueueTriggers {
        publish_dht_ops: publish_trigger,
        integrate_dht_ops: integration_trigger,
        ..
    } = trigger;
    // Using iterators is fine in this function as there can only be a maximum of 8 actions.
    let (this_cells_action_hash, entry_hash) = match signed_actions
        .iter()
        .find(|h| *h.0.author() == author)
        .and_then(|sh| {
            sh.0.entry_hash()
                .cloned()
                .map(|eh| (ActionHash::with_data_sync(&sh.0), eh))
        }) {
        Some(h) => h,
        None => return Ok(()),
    };

    // Do a quick check to see if this entry hash matches
    // the current locked session so we don't check signatures
    // unless there is an active session.
    let reader_closure = {
        let entry_hash = entry_hash.clone();
        let this_cells_action_hash = this_cells_action_hash.clone();
        let author = author.clone();
        move |txn: Transaction| {
            if holochain_state::chain_lock::is_chain_locked(&txn, &[], &author)? {
                let transaction: holochain_state::prelude::Txn = (&txn).into();
                if transaction.contains_entry(&entry_hash)? {
                    // If this is a countersigning session we can grab all the ops
                    // for this cells action so we can check if we need to self publish them.
                    let r: Result<_, _> = txn
                        .prepare(
                            "SELECT basis_hash, hash FROM DhtOp WHERE action_hash = :action_hash",
                        )?
                        .query_map(
                            named_params! {
                                ":action_hash": this_cells_action_hash
                            },
                            |row| {
                                let hash: DhtOpHash = row.get("hash")?;
                                let basis: OpBasis = row.get("basis_hash")?;
                                Ok((hash, basis))
                            },
                        )?
                        .collect();
                    return Ok(r?);
                }
            }
            StateMutationResult::Ok(Vec::with_capacity(0))
        }
    };
    let this_cell_actions_op_basis_hashes: Vec<(DhtOpHash, OpBasis)> =
        authored_db.async_reader(reader_closure).await?;

    // If there is no active session then we can short circuit.
    if this_cell_actions_op_basis_hashes.is_empty() {
        return Ok(());
    }

    // Verify signatures of actions.
    let mut i_am_an_author = false;
    for SignedAction(action, signature) in &signed_actions {
        if !action.author().verify_signature(signature, action).await {
            return Ok(());
        }
        if action.author() == &author {
            i_am_an_author = true;
        }
    }
    // Countersigning success is ultimately between authors to agree and publish.
    if !i_am_an_author {
        return Ok(());
    }

    // Hash actions.
    let incoming_actions: Vec<_> = signed_actions
        .iter()
        .map(|SignedAction(h, _)| ActionHash::with_data_sync(h))
        .collect();

    let result = authored_db
        .async_commit({
            let author = author.clone();
            let entry_hash = entry_hash.clone();
            move |txn| {
            if let Some((cs_entry_hash, cs)) = current_countersigning_session(txn, Arc::new(author.clone()))? {
                // Check we have the right session.
                if cs_entry_hash == entry_hash {
                    let weight = weigh_placeholder();
                    let stored_actions = cs.build_action_set(entry_hash, weight)?;
                    if stored_actions.len() == incoming_actions.len() {
                        // Check all stored action hashes match an incoming action hash.
                        if stored_actions.iter().all(|h| {
                            let h = ActionHash::with_data_sync(h);
                            incoming_actions.iter().any(|i| *i == h)
                        }) {
                            // All checks have passed so unlock the chain.
                            mutations::unlock_chain(txn, &author)?;
                            // Update ops to publish.
                            txn.execute("UPDATE DhtOp SET withhold_publish = NULL WHERE action_hash = :action_hash",
                            named_params! {
                                ":action_hash": this_cells_action_hash,
                                }
                            ).map_err(holochain_state::prelude::StateMutationError::from)?;
                            return Ok(true);
                        }
                    }
                }
            }
            SourceChainResult::Ok(false)
        }})
        .await?;

    if result {
        // If all signatures are valid (above) and i signed then i must have
        // validated it previously so i now agree that i authored it.
        authored_ops_to_dht_db_without_check(
            this_cell_actions_op_basis_hashes
                .into_iter()
                .map(|(op_hash, _)| op_hash)
                .collect(),
            &(authored_db.into()),
            &dht_db,
            &dht_db_cache,
        )
        .await?;
        integration_trigger.trigger(&"countersigning_success");
        // Publish other signers agent activity ops to their agent activity authorities.
        for SignedAction(action, signature) in signed_actions {
            if *action.author() == author {
                continue;
            }
            let op = DhtOp::RegisterAgentActivity(signature, action);
            let basis = op.dht_basis();
            if let Err(e) = network.publish_countersign(false, basis, op).await {
                tracing::error!(
                    "Failed to publish to other countersigners agent authorities because of: {:?}",
                    e
                );
            }
        }
        // Signal to the UI.
        signal.send(Signal::System(SystemSignal::SuccessfulCountersigning(
            entry_hash,
        )))?;

        publish_trigger.trigger(&"publish countersigning_success");
    }
    Ok(())
}
More examples
Hide additional examples
src/core/ribosome/host_fn/update.rs (line 33)
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
pub fn update<'a>(
    _ribosome: Arc<impl RibosomeT>,
    call_context: Arc<CallContext>,
    input: UpdateInput,
) -> Result<ActionHash, RuntimeError> {
    match HostFnAccess::from(&call_context.host_context()) {
        HostFnAccess {
            write_workspace: Permission::Allow,
            ..
        } => {
            // destructure the args out into an app type def id and entry
            let UpdateInput {
                original_action_address,
                entry,
                chain_top_ordering,
            } = input;

            let (original_entry_address, entry_type) =
                get_original_entry_data(call_context.clone(), original_action_address.clone())?;

            let weight = weigh_placeholder();

            // Countersigned entries have different action handling.
            match entry {
                Entry::CounterSign(_, _) => tokio_helper::block_forever_on(async move {
                    call_context
                        .host_context
                        .workspace_write()
                        .source_chain()
                        .as_ref()
                        .expect("Must have source chain if write_workspace access is given")
                        .put_countersigned(entry, chain_top_ordering, weight)
                        .await
                        .map_err(|source_chain_error| -> RuntimeError {
                            wasm_error!(WasmErrorInner::Host(source_chain_error.to_string())).into()
                        })
                }),
                _ => {
                    // build the entry hash
                    let entry_hash = EntryHash::with_data_sync(&entry);

                    // build an action for the entry being updated
                    let action_builder = builder::Update {
                        original_entry_address,
                        original_action_address,
                        entry_type,
                        entry_hash,
                    };
                    let workspace = call_context.host_context.workspace_write();

                    // return the hash of the updated entry
                    // note that validation is handled by the workflow
                    // if the validation fails this update will be rolled back by virtue of the DB transaction
                    // being atomic
                    tokio_helper::block_forever_on(async move {
                        let source_chain = workspace
                            .source_chain()
                            .as_ref()
                            .expect("Must have source chain if write_workspace access is given");
                        // push the action and the entry into the source chain
                        let action_hash = source_chain
                            .put_weightless(action_builder, Some(entry), chain_top_ordering)
                            .await
                            .map_err(|source_chain_error| -> RuntimeError {
                                wasm_error!(WasmErrorInner::Host(source_chain_error.to_string()))
                                    .into()
                            })?;
                        Ok(action_hash)
                    })
                }
            }
        }
        _ => Err(wasm_error!(WasmErrorInner::Host(
            RibosomeError::HostFnPermissions(
                call_context.zome.zome_name().clone(),
                call_context.function_name().clone(),
                "update".into()
            )
            .to_string()
        ))
        .into()),
    }
}
src/core/ribosome/host_fn/create.rs (line 30)
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
pub fn create<'a>(
    _ribosome: Arc<impl RibosomeT>,
    call_context: Arc<CallContext>,
    input: CreateInput,
) -> Result<ActionHash, RuntimeError> {
    match HostFnAccess::from(&call_context.host_context()) {
        HostFnAccess {
            write_workspace: Permission::Allow,
            ..
        } => {
            let CreateInput {
                entry_location,
                entry_visibility,
                entry,
                chain_top_ordering,
            } = input;

            let weight = weigh_placeholder();

            // Countersigned entries have different action handling.
            match entry {
                Entry::CounterSign(_, _) => tokio_helper::block_forever_on(async move {
                    call_context
                        .host_context
                        .workspace_write()
                        .source_chain()
                        .as_ref()
                        .expect("Must have source chain if write_workspace access is given")
                        .put_countersigned(entry, chain_top_ordering, weight)
                        .await
                        .map_err(|source_chain_error| -> RuntimeError {
                            wasm_error!(WasmErrorInner::Host(source_chain_error.to_string())).into()
                        })
                }),
                _ => {
                    // build the entry hash
                    let entry_hash = EntryHash::with_data_sync(&entry);

                    // extract the entry defs for a zome
                    let entry_type = match entry_location {
                        EntryDefLocation::App(AppEntryDefLocation {
                            zome_index,
                            entry_def_index,
                        }) => {
                            let app_entry_def =
                            AppEntryDef::new(entry_def_index, zome_index, entry_visibility);
                            EntryType::App(app_entry_def)
                        }
                        EntryDefLocation::CapGrant => EntryType::CapGrant,
                        EntryDefLocation::CapClaim => EntryType::CapClaim,
                    };

                    // build an action for the entry being committed
                    let action_builder = builder::Create {
                        entry_type,
                        entry_hash,
                    };

                    // return the hash of the committed entry
                    // note that validation is handled by the workflow
                    // if the validation fails this commit will be rolled back by virtue of the DB transaction
                    // being atomic
                    tokio_helper::block_forever_on(async move {
                        // push the action and the entry into the source chain
                        call_context
                            .host_context
                            .workspace_write()
                            .source_chain()
                            .as_ref()
                            .expect("Must have source chain if write_workspace access is given")
                            .put_weightless(action_builder, Some(entry), chain_top_ordering)
                            .await
                            .map_err(|source_chain_error| -> RuntimeError {
                                wasm_error!(WasmErrorInner::Host(source_chain_error.to_string()))
                                    .into()
                            })
                    })
                }
            }
        }
        _ => Err(wasm_error!(WasmErrorInner::Host(
            RibosomeError::HostFnPermissions(
                call_context.zome.zome_name().clone(),
                call_context.function_name().clone(),
                "create".into(),
            )
            .to_string(),
        ))
        .into()),
    }
}