use std::thread;
use std::time::{Duration, Instant};
use serde_json::{json, Value as Json};
use stratum_node_core::{
admission_notice_v1_sha256, AdmissionClaim, AdmissionFields, DidNostr, InvitationId,
MemberState, NostrSecretKey, PodPath, Sha256Digest,
};
use crate::client::{self, MAX_RESPONSE_BYTES};
use crate::error::CliError;
use crate::exit;
use crate::gate::{GateClient, Precondition, Request, Route, ANY, JSON};
use crate::origin::GateTarget;
use crate::output::sanitize;
use crate::session::{to_body, Confirmation, Session};
use crate::wire::{ConfirmRequest, ConfirmResponse, NoticeResponse, OperationResponse};
const NOTICE: &str = "/api/v1/admission/notice";
const REDEEM: &str = "/api/v1/admission/redeem";
const OPERATION: &str = "/api/v1/admission/operation";
const CONFIRM: &str = "/api/v1/admission/confirm";
pub const DEFAULT_WAIT: Duration = Duration::from_secs(120);
const FIRST_POLL_INTERVAL: Duration = Duration::from_millis(250);
const MAX_POLL_INTERVAL: Duration = Duration::from_secs(2);
const PROBE_PREFIX: &str = "stratum-join-probe-";
#[derive(Debug, Clone)]
pub struct JoinOptions {
pub invitation: InvitationId,
pub node: DidNostr,
pub wait: Duration,
pub confirmation: Confirmation,
}
#[derive(Debug, Default)]
struct Progress {
redeemed: bool,
resent: bool,
}
impl Session {
pub fn join(&self, target: &GateTarget, options: &JoinOptions) -> Result<u8, CliError> {
let key = self.key()?;
let me = key.public();
let gate = GateClient::new(target.clone());
let pod_url = target.origin().url(PodPath::pod_root(&me).as_str());
let notice = fetch_notice(&gate, options)?;
let mut progress = Progress::default();
let mut operation = if let Some(operation) = own_operation(&gate, &key)? {
self.output().note(&format!(
"{me} is already a member of this node ({}); continuing",
operation.state
))?;
operation
} else {
self.show_notice(¬ice)?;
if !self.confirmed(
"join this node, accepting the notice above?",
options.confirmation,
)? {
self.output().json(&json!({"joined": false}))?;
return Err(CliError::NotConfirmed);
}
let operation = self.redeem(&gate, &key, options, &mut progress)?;
progress.redeemed = true;
operation
};
check_operation(&operation, me, &pod_url)?;
self.output().note(&format!(
"operation {}: {}",
operation.operation_id, operation.state
))?;
if !matches!(
operation.state,
MemberState::Provisioned | MemberState::Active
) {
operation = self.wait_provisioned(&gate, &key, &pod_url, options.wait)?;
}
let (probe, probe_sha256) = self.probe(&gate, &key, &me)?;
let body = to_body(&ConfirmRequest {
node: options.node,
operation_id: &operation.operation_id,
})?;
let (confirmed, _raw): (ConfirmResponse, Json) = gate
.fetch(
&Request::new("POST", CONFIRM, JSON).with_body(&body, JSON),
Some(&key),
MAX_RESPONSE_BYTES,
)?
.into_json(Route::Admission)?;
if confirmed.did != me || confirmed.pod_url != pod_url {
return Err(CliError::Refused(format!(
"the confirmation names {} at {}, not {me} at {pod_url}",
confirmed.did,
sanitize(&confirmed.pod_url)
)));
}
if confirmed.state != MemberState::Active {
return Err(CliError::Refused(format!(
"the node reports the member {} after confirming, not active",
confirmed.state
)));
}
self.output().json(&json!({
"joined": true,
"did": me,
"node": options.node,
"origin": target.origin().as_str(),
"invitation": options.invitation,
"operation_id": operation.operation_id,
"state": confirmed.state,
"pod_url": pod_url,
"redeemed": progress.redeemed,
"resent": progress.resent,
"probe": {"path": probe, "sha256": probe_sha256},
}))?;
self.output().line(&format!("member: {me}"))?;
self.output().line("state: active")?;
self.output().line(&format!("pod: {pod_url}"))?;
Ok(exit::OK)
}
fn show_notice(&self, notice: &NoticeResponse) -> Result<(), CliError> {
self.output().note(&format!(
"admission notice from {} (sha256 {}):",
notice.node, notice.notice_sha256
))?;
self.output().note("")?;
self.output().note(&sanitize(¬ice.notice))?;
self.output().note("")
}
fn redeem(
&self,
gate: &GateClient,
key: &NostrSecretKey,
options: &JoinOptions,
progress: &mut Progress,
) -> Result<OperationResponse, CliError> {
let claim = AdmissionClaim::new(AdmissionFields {
node: options.node,
subject: key.public(),
invitation: options.invitation,
notice_sha256: admission_notice_v1_sha256(),
});
let request = Request::new("POST", REDEEM, JSON).with_body(claim.as_bytes(), JSON);
let authorization = gate.sign(key, &request)?;
let response = match gate.fetch_with(&request, Some(&authorization), MAX_RESPONSE_BYTES) {
Err(CliError::Unreachable { message, .. }) => {
self.output().note(&format!(
"the redemption response was lost ({message}); resending the identical \
signed request once"
))?;
progress.resent = true;
gate.fetch_with(&request, Some(&authorization), MAX_RESPONSE_BYTES)?
}
other => other?,
};
let (operation, _raw): (OperationResponse, Json) = response.into_json(Route::Admission)?;
if operation.state == MemberState::Cancelled {
return Err(cancelled());
}
Ok(operation)
}
fn wait_provisioned(
&self,
gate: &GateClient,
key: &NostrSecretKey,
pod_url: &str,
wait: Duration,
) -> Result<OperationResponse, CliError> {
let deadline = Instant::now() + wait;
let mut interval = FIRST_POLL_INTERVAL;
let mut shown_error: Option<String> = None;
loop {
let now = Instant::now();
if now >= deadline {
let last = shown_error
.map(|err| format!("; the node's last error: {err}"))
.unwrap_or_default();
return Err(CliError::TimedOut(format!(
"the pod was not provisioned within {} s{last}; rerun the same join command \
to continue",
wait.as_secs()
)));
}
thread::sleep(interval.min(deadline - now));
interval = (interval * 2).min(MAX_POLL_INTERVAL);
let (operation, _raw): (OperationResponse, Json) = gate
.fetch(
&Request::new("GET", OPERATION, JSON),
Some(key),
MAX_RESPONSE_BYTES,
)?
.into_json(Route::Admission)?;
check_operation(&operation, key.public(), pod_url)?;
if let Some(err) = &operation.last_error {
let err = sanitize(err);
if shown_error.as_deref() != Some(err.as_str()) {
self.output()
.note(&format!("the node reports a provisioning error: {err}"))?;
shown_error = Some(err);
}
}
match operation.state {
MemberState::Provisioned | MemberState::Active => return Ok(operation),
MemberState::Cancelled => return Err(cancelled()),
_ => {}
}
}
}
fn probe(
&self,
gate: &GateClient,
key: &NostrSecretKey,
me: &DidNostr,
) -> Result<(PodPath, Sha256Digest), CliError> {
let random = client::random_32()?;
let name = format!("{PROBE_PREFIX}{}", hex::encode(&random[..8]));
let path = PodPath::pod_root(me)
.join(&name)
.map_err(|err| CliError::Local(format!("probe path: {err}")))?;
let content = format!("stratum join probe {}\n", hex::encode(&random[8..24]));
let written = Sha256Digest::of(content.as_bytes());
let put = gate.fetch(
&Request::new("PUT", path.as_str(), ANY)
.with_body(content.as_bytes(), "text/plain")
.with_precondition(Precondition::CreateOnly),
Some(key),
MAX_RESPONSE_BYTES,
)?;
if !put.head.is_success() {
return Err(put.into_error(Route::Pod));
}
let get = gate.fetch(
&Request::new("GET", path.as_str(), ANY),
Some(key),
MAX_RESPONSE_BYTES,
)?;
if !get.head.is_success() {
return Err(get.into_error(Route::Pod));
}
if get.body != content.as_bytes() {
return Err(CliError::Refused(format!(
"the probe {path} read back {} bytes that differ from the {} written",
get.body.len(),
content.len()
)));
}
let delete = gate.fetch(
&Request::new("DELETE", path.as_str(), ANY),
Some(key),
MAX_RESPONSE_BYTES,
)?;
if !delete.head.is_success() {
return Err(delete.into_error(Route::Pod));
}
self.output()
.note(&format!("probe {path} written, read back and deleted"))?;
Ok((path, written))
}
}
fn fetch_notice(gate: &GateClient, options: &JoinOptions) -> Result<NoticeResponse, CliError> {
let (notice, _raw): (NoticeResponse, Json) = gate
.fetch(&Request::new("GET", NOTICE, JSON), None, MAX_RESPONSE_BYTES)?
.into_json(Route::Admission)?;
if notice.node != options.node {
return Err(CliError::Refused(format!(
"the node at this origin is {}, not {} named by the invitation",
notice.node, options.node
)));
}
let origin = gate.target().origin().as_str();
if notice.origin != origin {
return Err(CliError::Refused(format!(
"the node reports its origin as {}, not {origin}",
sanitize(¬ice.origin)
)));
}
let received = Sha256Digest::of(notice.notice.as_bytes());
if received != notice.notice_sha256 {
return Err(CliError::Refused(format!(
"the notice text hashes to {received}, not to the {} the node reports",
notice.notice_sha256
)));
}
let known = admission_notice_v1_sha256();
if received != known {
return Err(CliError::Refused(format!(
"the node's notice (sha256 {received}) is not the admission notice this client \
knows (sha256 {known}); nothing was signed"
)));
}
Ok(notice)
}
fn own_operation(
gate: &GateClient,
key: &NostrSecretKey,
) -> Result<Option<OperationResponse>, CliError> {
let response = gate.fetch(
&Request::new("GET", OPERATION, JSON),
Some(key),
MAX_RESPONSE_BYTES,
)?;
if matches!(response.head.status, 403 | 404) {
return Ok(None);
}
let (operation, _raw): (OperationResponse, Json) = response.into_json(Route::Admission)?;
if operation.state == MemberState::Cancelled {
return Err(cancelled());
}
Ok(Some(operation))
}
fn check_operation(
operation: &OperationResponse,
me: DidNostr,
pod_url: &str,
) -> Result<(), CliError> {
if operation.did != me {
return Err(CliError::Refused(format!(
"the node answered with the operation of {}, not of {me}",
operation.did
)));
}
let pending = operation.state == MemberState::Reserved && operation.pod_url.is_empty();
if operation.pod_url != pod_url && !pending {
return Err(CliError::Refused(format!(
"the node reports pod url {}, not {pod_url}",
sanitize(&operation.pod_url)
)));
}
Ok(())
}
fn cancelled() -> CliError {
CliError::Refused(
"the administrator cancelled this membership; ask them for a new invitation".to_owned(),
)
}