use chia_protocol::SpendBundle;
use crate::mint::chain::{ChainUnavailable, PushOutcome, SpendPublisher};
pub const COINSET_MAINNET_PUSH_URL: &str = "https://api.coinset.org/push_tx";
const MAX_QUOTED_BODY: usize = 400;
const PENDING_ASSERTIONS: [&str; 4] = [
"ASSERT_HEIGHT_ABSOLUTE_FAILED",
"ASSERT_HEIGHT_RELATIVE_FAILED",
"ASSERT_SECONDS_ABSOLUTE_FAILED",
"ASSERT_SECONDS_RELATIVE_FAILED",
];
const MEMPOOL_REFUSAL_MARKER: &str = "failed to include transaction";
const ALREADY_INCLUDING: &str = "already_including_transaction";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HttpAnswer {
pub status: u16,
pub body: String,
}
impl HttpAnswer {
pub fn new(status: u16, body: impl Into<String>) -> Self {
Self {
status,
body: body.into(),
}
}
}
pub trait PushTransport {
fn post_json(&self, url: &str, body: &str) -> Result<HttpAnswer, String>;
}
#[derive(Debug, Clone)]
pub struct CoinsetPublisher<T> {
transport: T,
url: String,
}
impl<T: PushTransport> CoinsetPublisher<T> {
pub fn new(transport: T, url: impl Into<String>) -> Self {
Self {
transport,
url: url.into(),
}
}
pub fn mainnet(transport: T) -> Self {
Self::new(transport, COINSET_MAINNET_PUSH_URL)
}
pub fn url(&self) -> &str {
&self.url
}
}
impl<T: PushTransport> SpendPublisher for CoinsetPublisher<T> {
fn push(&self, bundle: &SpendBundle) -> Result<PushOutcome, ChainUnavailable> {
let request = push_tx_request_json(bundle)
.map_err(|why| ChainUnavailable::new(format!("could not encode the bundle: {why}")))?;
let answer = self
.transport
.post_json(&self.url, &request)
.map_err(|why| ChainUnavailable::new(format!("{}: {why}", self.url)))?;
interpret_push_answer(&answer)
}
}
pub fn push_tx_request_json(bundle: &SpendBundle) -> Result<String, serde_json::Error> {
let mut request = serde_json::json!({ "spend_bundle": bundle });
prefix_every_byte_string(&mut request);
serde_json::to_string(&request)
}
fn prefix_every_byte_string(value: &mut serde_json::Value) {
match value {
serde_json::Value::String(hex) => {
if !hex.starts_with("0x") {
hex.insert_str(0, "0x");
}
}
serde_json::Value::Array(items) => items.iter_mut().for_each(prefix_every_byte_string),
serde_json::Value::Object(fields) => fields
.iter_mut()
.for_each(|(_, field)| prefix_every_byte_string(field)),
_ => {}
}
}
pub fn interpret_push_answer(answer: &HttpAnswer) -> Result<PushOutcome, ChainUnavailable> {
let Ok(json) = serde_json::from_str::<serde_json::Value>(&answer.body) else {
return Err(unsettled(answer, "the body is not JSON"));
};
if let Some(reason) = json.get("error").and_then(serde_json::Value::as_str) {
return classify_error(answer, reason);
}
match json.get("status").and_then(serde_json::Value::as_str) {
Some("SUCCESS") => Ok(PushOutcome::Accepted),
Some("PENDING") => Err(unsettled(answer, "the mempool answered PENDING")),
Some("FAILED") => Ok(PushOutcome::Rejected {
reason: quote(&answer.body),
}),
Some(other) => Err(unsettled(
answer,
&format!("unrecognised mempool status {other:?}"),
)),
None => Err(unsettled(
answer,
"the body states neither status nor error",
)),
}
}
fn classify_error(answer: &HttpAnswer, reason: &str) -> Result<PushOutcome, ChainUnavailable> {
let lowered = reason.to_ascii_lowercase();
if lowered.contains(ALREADY_INCLUDING) {
return Ok(PushOutcome::AlreadyInMempool);
}
if PENDING_ASSERTIONS
.iter()
.any(|assertion| reason.contains(assertion))
{
return Err(unsettled(
answer,
"the bundle failed a height/seconds assertion, so the node is holding it",
));
}
if lowered.contains(MEMPOOL_REFUSAL_MARKER) {
return Ok(PushOutcome::Rejected {
reason: quote(reason),
});
}
Err(unsettled(
answer,
"the error is not a recognisable mempool decision",
))
}
fn unsettled(answer: &HttpAnswer, why: &str) -> ChainUnavailable {
ChainUnavailable::new(format!(
"the push outcome is unknown ({why}); HTTP {} said: {}",
answer.status,
quote(&answer.body)
))
}
fn quote(text: &str) -> String {
let trimmed = text.trim();
match trimmed.char_indices().nth(MAX_QUOTED_BODY) {
Some((cut, _)) => format!("{}…", &trimmed[..cut]),
None => trimmed.to_owned(),
}
}
#[cfg(feature = "coinset-push")]
mod blocking {
use std::time::Duration;
use super::{HttpAnswer, PushTransport};
const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
const CALL_TIMEOUT: Duration = Duration::from_secs(60);
#[derive(Debug, Clone)]
pub struct BlockingHttpTransport {
agent: ureq::Agent,
}
impl BlockingHttpTransport {
pub fn new() -> Self {
Self {
agent: ureq::AgentBuilder::new()
.timeout_connect(CONNECT_TIMEOUT)
.timeout(CALL_TIMEOUT)
.build(),
}
}
}
impl Default for BlockingHttpTransport {
fn default() -> Self {
Self::new()
}
}
impl PushTransport for BlockingHttpTransport {
fn post_json(&self, url: &str, body: &str) -> Result<HttpAnswer, String> {
let response = self
.agent
.post(url)
.set("Content-Type", "application/json")
.send_string(body);
let (status, reader) = match response {
Ok(ok) => (ok.status(), ok),
Err(ureq::Error::Status(status, raised)) => (status, raised),
Err(transport) => return Err(transport.to_string()),
};
let text = reader
.into_string()
.map_err(|why| format!("the response body could not be read: {why}"))?;
Ok(HttpAnswer::new(status, text))
}
}
}
#[cfg(feature = "coinset-push")]
pub use blocking::BlockingHttpTransport;
#[cfg(test)]
mod tests {
use std::cell::RefCell;
use chia_bls::Signature;
use chia_protocol::{Bytes32, Coin, CoinSpend, Program};
use super::*;
struct StubTransport {
answer: Result<HttpAnswer, String>,
calls: RefCell<Vec<(String, String)>>,
}
impl StubTransport {
fn answering(status: u16, body: &str) -> Self {
Self {
answer: Ok(HttpAnswer::new(status, body)),
calls: RefCell::new(Vec::new()),
}
}
fn failing(why: &str) -> Self {
Self {
answer: Err(why.to_owned()),
calls: RefCell::new(Vec::new()),
}
}
}
impl PushTransport for StubTransport {
fn post_json(&self, url: &str, body: &str) -> Result<HttpAnswer, String> {
self.calls
.borrow_mut()
.push((url.to_owned(), body.to_owned()));
self.answer.clone()
}
}
fn a_bundle() -> SpendBundle {
let coin = Coin::new(Bytes32::new([1; 32]), Bytes32::new([2; 32]), 3);
let spend = CoinSpend::new(coin, Program::from(vec![0x80]), Program::from(vec![0x80]));
SpendBundle::new(vec![spend], Signature::default())
}
fn push_through(transport: StubTransport) -> Result<PushOutcome, ChainUnavailable> {
CoinsetPublisher::new(transport, "https://example.invalid/push_tx").push(&a_bundle())
}
#[test]
fn a_success_status_is_accepted() {
let outcome = push_through(StubTransport::answering(
200,
r#"{"status":"SUCCESS","success":true}"#,
));
assert_eq!(outcome.unwrap(), PushOutcome::Accepted);
}
#[test]
fn an_already_including_error_is_success_not_a_rejection() {
let outcome = push_through(StubTransport::answering(
400,
r#"{"success":false,"error":"Failed to include transaction abcd, error ALREADY_INCLUDING_TRANSACTION"}"#,
));
assert_eq!(outcome.unwrap(), PushOutcome::AlreadyInMempool);
}
#[test]
fn a_mempool_refusal_is_a_value_not_an_error() {
let outcome = push_through(StubTransport::answering(
400,
r#"{"success":false,"error":"Failed to include transaction abcd, error DOUBLE_SPEND"}"#,
));
let PushOutcome::Rejected { reason } =
outcome.expect("a refusal is an answer, not an error")
else {
panic!("a stated mempool refusal must be Rejected");
};
assert!(reason.contains("DOUBLE_SPEND"), "reason was {reason:?}");
}
#[test]
fn coinset_states_a_refusal_at_http_200() {
let outcome = push_through(StubTransport::answering(
200,
r#"{"error":"Failed to include transaction 0xdead, error INVALID_SPEND_BUNDLE","structuredError":{"code":"TRANSACTION_FAILED","data":{"error":"INVALID_SPEND_BUNDLE","spend_name":"0xdead"}},"success":false,"traceback":"Traceback (most recent call last): ...","tx_id":"0xdead"}"#,
));
let PushOutcome::Rejected { reason } =
outcome.expect("a refusal is an answer, whatever status carried it")
else {
panic!("a 200-carried mempool refusal must still be Rejected");
};
assert!(
reason.contains("INVALID_SPEND_BUNDLE"),
"reason was {reason:?}"
);
}
#[test]
fn a_two_hundred_carrying_an_unrecognised_error_is_still_unsettled() {
let outcome = push_through(StubTransport::answering(
200,
r#"{"error":"upstream request timed out","success":false}"#,
));
outcome.expect_err("an unrecognised error is unknown, never a refusal");
}
#[test]
fn a_failed_status_is_a_rejection() {
let outcome = push_through(StubTransport::answering(200, r#"{"status":"FAILED"}"#));
assert!(matches!(outcome, Ok(PushOutcome::Rejected { .. })));
}
#[test]
fn a_transport_failure_is_chain_unavailable() {
let outcome = push_through(StubTransport::failing("connection refused"));
let error = outcome.expect_err("a failure to ASK is never an answer");
assert!(
error.to_string().contains("connection refused"),
"error was {error}"
);
}
#[test]
fn an_unparseable_body_is_chain_unavailable() {
let outcome = push_through(StubTransport::answering(502, "<html>bad gateway</html>"));
assert!(outcome.is_err(), "a non-JSON body settles nothing");
}
#[test]
fn a_pending_verdict_is_unsettled_not_a_rejection() {
let by_status = push_through(StubTransport::answering(200, r#"{"status":"PENDING"}"#));
assert!(by_status.is_err(), "PENDING must never be Rejected");
let by_error = push_through(StubTransport::answering(
400,
r#"{"error":"Failed to include transaction abcd, error ASSERT_HEIGHT_ABSOLUTE_FAILED"}"#,
));
assert!(
by_error.is_err(),
"a held height assertion must never be Rejected"
);
}
#[test]
fn an_unrecognised_error_is_unsettled_not_a_rejection() {
let outcome = push_through(StubTransport::answering(
504,
r#"{"success":false,"error":"upstream request timeout"}"#,
));
assert!(outcome.is_err(), "an upstream error settles nothing");
}
#[test]
fn a_body_with_neither_status_nor_error_is_unsettled() {
let outcome = push_through(StubTransport::answering(200, r#"{"success":true}"#));
assert!(outcome.is_err(), "a bare success flag settles nothing");
}
#[test]
fn a_server_controlled_body_is_bounded_before_it_reaches_a_diagnostic() {
let flood = "x".repeat(10_000);
let outcome = push_through(StubTransport::answering(500, &flood));
let rendered = outcome.expect_err("not JSON").to_string();
assert!(
rendered.len() < MAX_QUOTED_BODY + 200,
"an unbounded body reached the diagnostic: {} chars",
rendered.len()
);
}
#[test]
fn the_bundle_is_posted_once_to_the_configured_url_in_push_tx_shape() {
let transport = StubTransport::answering(200, r#"{"status":"SUCCESS"}"#);
let publisher = CoinsetPublisher::new(transport, "https://example.invalid/push_tx");
publisher.push(&a_bundle()).expect("accepted");
let calls = publisher.transport.calls.borrow();
assert_eq!(
calls.len(),
1,
"push must never retry on its own initiative"
);
assert_eq!(calls[0].0, "https://example.invalid/push_tx");
let body: serde_json::Value = serde_json::from_str(&calls[0].1).expect("valid JSON");
let bundle = &body["spend_bundle"];
assert!(
bundle["aggregated_signature"].is_string(),
"body was {body:#}"
);
let spend = &bundle["coin_spends"][0];
assert!(spend["puzzle_reveal"].is_string(), "body was {body:#}");
assert!(spend["solution"].is_string(), "body was {body:#}");
assert!(
spend["coin"]["parent_coin_info"].is_string(),
"body was {body:#}"
);
assert!(
spend["coin"]["puzzle_hash"].is_string(),
"body was {body:#}"
);
assert_eq!(spend["coin"]["amount"], serde_json::json!(3));
}
fn each_string(value: &serde_json::Value, path: &str, visit: &mut impl FnMut(&str, &str)) {
match value {
serde_json::Value::String(text) => visit(path, text),
serde_json::Value::Array(items) => {
for (index, item) in items.iter().enumerate() {
each_string(item, &format!("{path}[{index}]"), visit);
}
}
serde_json::Value::Object(fields) => {
for (name, field) in fields {
each_string(field, &format!("{path}.{name}"), visit);
}
}
_ => {}
}
}
#[test]
fn every_hex_field_in_the_request_carries_the_0x_prefix_the_node_requires() {
let encoded = push_tx_request_json(&a_bundle()).expect("encodable");
let body: serde_json::Value = serde_json::from_str(&encoded).expect("valid JSON");
let mut bare = Vec::new();
each_string(&body, "$", &mut |path, text| {
if !text.starts_with("0x") {
bare.push(format!("{path} = {text:?}"));
}
});
assert!(
bare.is_empty(),
"the node rejects a bare hex byte-string; these lack the 0x prefix: {bare:#?}\nbody was {encoded}"
);
}
#[test]
fn an_already_prefixed_field_is_not_prefixed_twice() {
let encoded = push_tx_request_json(&a_bundle()).expect("encodable");
assert!(
!encoded.contains("0x0x"),
"a prefix was applied twice: {encoded}"
);
let body: serde_json::Value = serde_json::from_str(&encoded).expect("valid JSON");
assert_eq!(
body["spend_bundle"]["coin_spends"][0]["coin"]["parent_coin_info"],
serde_json::json!("0x0101010101010101010101010101010101010101010101010101010101010101")
);
}
#[test]
fn the_encoding_matches_the_body_mainnet_was_observed_to_parse() {
let encoded = push_tx_request_json(&a_bundle()).expect("encodable");
assert_eq!(
encoded,
r#"{"spend_bundle":{"aggregated_signature":"0xc00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","coin_spends":[{"coin":{"amount":3,"parent_coin_info":"0x0101010101010101010101010101010101010101010101010101010101010101","puzzle_hash":"0x0202020202020202020202020202020202020202020202020202020202020202"},"puzzle_reveal":"0x80","solution":"0x80"}]}}"#
);
}
#[test]
fn the_deserialisation_complaint_is_unknown_never_a_refusal() {
let outcome = interpret_push_answer(&HttpAnswer::new(
200,
r#"{"error":"bytes object is expected to start with 0x","structuredError":{"code":"UNKNOWN","data":{},"message":"bytes object is expected to start with 0x"},"success":false,"traceback":"Traceback (most recent call last):\n File \"/chia-blockchain/chia/rpc/util.py\", line 81, in inner\n res_object = await f(request_data)\n","tx_id":"0xdd6b873dd"}"#,
));
outcome.expect_err("a request-level parse error settles nothing about the mempool");
}
#[test]
fn the_answer_to_a_parsed_bundle_is_a_refusal() {
let outcome = interpret_push_answer(&HttpAnswer::new(
200,
r#"{"error":"Failed to include transaction dd6b873dd4965065ec31eb8e2f03ec8cb4bdc25b5ab590b722cdfa9d569030e8, error WRONG_PUZZLE_HASH","structuredError":{"code":"TRANSACTION_FAILED","data":{"error":"WRONG_PUZZLE_HASH","spend_name":"dd6b873dd4965065ec31eb8e2f03ec8cb4bdc25b5ab590b722cdfa9d569030e8"},"message":"Failed to include transaction"},"success":false}"#,
));
let PushOutcome::Rejected { reason } = outcome.expect("the mempool answered") else {
panic!("a parsed-then-refused bundle must be Rejected");
};
assert!(
reason.contains("WRONG_PUZZLE_HASH"),
"reason was {reason:?}"
);
}
#[cfg(feature = "coinset-push")]
#[test]
#[ignore = "posts to real mainnet"]
fn the_live_node_parses_our_encoding() {
let nonce = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.expect("a clock after 1970")
.as_nanos() as u64;
let coin = Coin::new(
Bytes32::new([1; 32]),
Bytes32::new([2; 32]),
nonce % 1_000_000,
);
let spend = CoinSpend::new(coin, Program::from(vec![0x80]), Program::from(vec![0x80]));
let bundle = SpendBundle::new(vec![spend], Signature::default());
let answer = BlockingHttpTransport::new()
.post_json(
COINSET_MAINNET_PUSH_URL,
&push_tx_request_json(&bundle).expect("encodable"),
)
.expect("mainnet answered");
println!("HTTP {}: {}", answer.status, answer.body);
assert!(
!answer.body.contains("expected to start with 0x"),
"the node still refused our encoding at the deserialiser: {}",
answer.body
);
assert!(
answer.body.contains("Failed to include transaction"),
"expected a mempool decision, proving the bundle parsed: {}",
answer.body
);
assert!(
matches!(
interpret_push_answer(&answer),
Ok(PushOutcome::Rejected { .. } | PushOutcome::AlreadyInMempool)
),
"a parsed bundle must yield the mempool's decision, not an unknown: {}",
answer.body
);
}
#[test]
fn the_mainnet_constructor_targets_coinset() {
let publisher = CoinsetPublisher::mainnet(StubTransport::answering(200, "{}"));
assert_eq!(publisher.url(), COINSET_MAINNET_PUSH_URL);
}
}