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
use crate::{Height, Timestamp, TxId};
use serde::Deserialize;
use std::fmt;
/// A broadcaster's claim reduced to the Lean hint vocabulary.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum HintStatus {
/// The broadcaster accepted the transaction.
Accepted,
/// The broadcaster reports the transaction seen on the network.
Seen,
/// The broadcaster claims a block at a height; never inclusion evidence.
Mined {
/// The height the broadcaster names.
height: Height,
},
/// The broadcaster reports the transaction mined in a block that went stale.
StaleBlock,
/// The broadcaster reports a rejection.
Rejected {
/// The broadcaster's reason, or its status word when it gave none.
reason: String,
},
/// The broadcaster reports a double spend.
DoubleSpend {
/// The competing txids the broadcaster names.
competitors: Vec<TxId>,
},
/// The broadcaster reports the transaction in its orphan mempool.
OrphanMempool,
/// A status the vocabulary does not reduce to any other hint.
Unknown,
}
/// An observed hint, carrying its source and host supplied time.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Hint {
/// The host's name for the broadcaster or feed that supplied the hint.
pub source: String,
/// The claim, in the Lean hint vocabulary.
pub status: HintStatus,
/// When the host observed the hint, on its own clock.
pub observed: Timestamp,
/// The original broadcaster metadata, when reduced through `Verdict`.
/// This retains the raw status, reason and named competitors for re-asks.
pub verdict: Option<Verdict>,
}
impl Hint {
/// A reduced hint, for hosts whose source already supplies the Lean vocabulary.
pub fn new(source: impl Into<String>, status: HintStatus, observed: Timestamp) -> Self {
Self {
source: source.into(),
status,
observed,
verdict: None,
}
}
}
/// Raw broadcaster metadata. HTTP acceptance is not chain evidence.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Verdict {
/// The raw `txStatus` word, as the body spelled it.
pub status: String,
/// The raw `blockHeight`, when present.
pub height: Option<Height>,
/// The raw `extraInfo`, when present.
pub reason: Option<String>,
/// The `competingTxs`, lowercased and checked for shape and uniqueness.
pub competitors: Vec<TxId>,
}
impl Verdict {
/// Read an ARC body as metadata, checking its echoed txid and the bounded
/// status vocabulary at bsv-rs@7bc623c. HTTP status is never consulted.
///
/// # Errors
///
/// [`VerdictError::Shape`] when the body does not decode,
/// [`VerdictError::TxidMismatch`] when it echoes another or a malformed
/// txid, [`VerdictError::InvalidMetadata`] when its text or competitors
/// break the bounds, and [`VerdictError::UnknownStatus`] for a status word
/// outside the vocabulary.
pub fn from_arc_body(expected_txid: &str, bytes: &[u8]) -> Result<Self, VerdictError> {
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Body {
txid: Option<String>,
tx_status: String,
block_height: Option<Height>,
extra_info: Option<String>,
competing_txs: Option<Vec<TxId>>,
}
let body: Body =
serde_json::from_slice(bytes).map_err(|e| VerdictError::Shape(e.to_string()))?;
if body
.txid
.as_deref()
.is_some_and(|txid| !is_txid(txid) || !txid.eq_ignore_ascii_case(expected_txid))
{
return Err(VerdictError::TxidMismatch);
}
if !bounded_text(&body.tx_status, 128, false)
|| body
.extra_info
.as_deref()
.is_some_and(|info| !bounded_text(info, 8_192, true))
{
return Err(VerdictError::InvalidMetadata);
}
let competitors: Vec<_> = body
.competing_txs
.unwrap_or_default()
.into_iter()
.map(|id| id.to_ascii_lowercase())
.collect();
if competitors.len() > 256
|| competitors.iter().any(|id| !is_txid(id))
|| competitors
.iter()
.collect::<std::collections::BTreeSet<_>>()
.len()
!= competitors.len()
{
return Err(VerdictError::InvalidMetadata);
}
let known = matches!(
body.tx_status.to_ascii_uppercase().as_str(),
"SUCCESS"
| "UNKNOWN"
| "RECEIVED"
| "QUEUED"
| "STORED"
| "ANNOUNCED_TO_NETWORK"
| "REQUESTED_BY_NETWORK"
| "SENT_TO_NETWORK"
| "ACCEPTED_BY_NETWORK"
| "SEEN_ON_NETWORK"
| "SEEN_MULTIPLE_NODES"
| "MINED"
| "CONFIRMED"
| "IMMUTABLE"
| "MINED_IN_STALE_BLOCK"
| "REJECTED"
| "INVALID"
| "MALFORMED"
| "DOUBLE_SPEND_ATTEMPTED"
| "UTXO_SPENT"
| "SEEN_IN_ORPHAN_MEMPOOL"
| "PENDING_RETRY"
| "STUMP_PROCESSING"
);
if !known {
return Err(VerdictError::UnknownStatus(body.tx_status));
}
Ok(Self {
status: body.tx_status,
height: body.block_height,
reason: body.extra_info,
competitors,
})
}
/// Interpret a status as a hint; no result is a node verdict or a proof.
pub fn into_hint(self, source: impl Into<String>, observed: Timestamp) -> Hint {
let status = match self.status.to_ascii_uppercase().as_str() {
"SUCCESS"
| "SENT_TO_NETWORK"
| "RECEIVED"
| "QUEUED"
| "STORED"
| "ANNOUNCED_TO_NETWORK"
| "REQUESTED_BY_NETWORK"
| "ACCEPTED_BY_NETWORK" => HintStatus::Accepted,
"SEEN_ON_NETWORK" | "SEEN_MULTIPLE_NODES" => HintStatus::Seen,
"MINED" | "CONFIRMED" | "IMMUTABLE" => self
.height
.map_or(HintStatus::Unknown, |height| HintStatus::Mined { height }),
"MINED_IN_STALE_BLOCK" | "REORG_UNMINED" | "REORG_UNCONFIRMED" => {
HintStatus::StaleBlock
}
"SEEN_IN_ORPHAN_MEMPOOL" => HintStatus::OrphanMempool,
"DOUBLE_SPEND_ATTEMPTED" | "UTXO_SPENT" => HintStatus::DoubleSpend {
competitors: self.competitors.clone(),
},
"REJECTED" | "INVALID" | "MALFORMED" => HintStatus::Rejected {
reason: self
.reason
.clone()
.filter(|s| !s.is_empty())
.unwrap_or_else(|| self.status.clone()),
},
_ => HintStatus::Unknown,
};
let status = if self
.reason
.as_deref()
.is_some_and(|r| r.eq_ignore_ascii_case("reorg_unmined"))
{
HintStatus::StaleBlock
} else if self.status.to_ascii_uppercase().contains("ORPHAN")
|| self
.reason
.as_deref()
.is_some_and(|r| r.to_ascii_uppercase().contains("ORPHAN"))
{
HintStatus::OrphanMempool
} else if !self.competitors.is_empty()
&& matches!(status, HintStatus::Accepted | HintStatus::Seen)
{
// A named competitor cannot disappear behind an accepting word.
HintStatus::DoubleSpend {
competitors: self.competitors.clone(),
}
} else {
status
};
Hint {
source: source.into(),
status,
observed,
verdict: Some(self),
}
}
}
/// An invalid broadcaster body is a reported fault, never chain evidence.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum VerdictError {
/// The expected fields cannot be decoded.
Shape(String),
/// The body names another transaction or a malformed identifier.
TxidMismatch,
/// Text or competing identifiers violate the pinned metadata bounds.
InvalidMetadata,
/// The sender uses a word this adapter does not know.
UnknownStatus(String),
}
impl fmt::Display for VerdictError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{self:?}")
}
}
impl std::error::Error for VerdictError {}
fn is_txid(value: &str) -> bool {
value.len() == 64 && value.bytes().all(|b| b.is_ascii_hexdigit())
}
fn bounded_text(value: &str, max: usize, empty: bool) -> bool {
(empty || !value.is_empty())
&& value.len() <= max
&& !value
.chars()
.any(|c| matches!(c as u32, 0..=31 | 127..=159))
}