From 350d24d284a179e9c1c103433dc4f0dc3b3f424a Mon Sep 17 00:00:00 2001 From: Joe Ardent Date: Sun, 9 Jun 2024 14:11:52 -0700 Subject: [PATCH] ensure aborted transactions don't get written --- gg-txn/src/main.rs | 32 ++++++++++++++++++++++---------- 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/gg-txn/src/main.rs b/gg-txn/src/main.rs index 9e61af6..402a4e3 100644 --- a/gg-txn/src/main.rs +++ b/gg-txn/src/main.rs @@ -1,6 +1,6 @@ use std::collections::HashMap; -use nebkor_maelstrom::{mk_payload, Body, Message, Node, Runner}; +use nebkor_maelstrom::{mk_payload, Body, ErrorCode, Message, Node, Runner}; use serde_json::Value; type Txn = Vec; @@ -44,6 +44,7 @@ impl TANode { fn transact(&mut self, txn: &Txn) -> (Txn, Txn) { let mut out = Txn::with_capacity(txn.len()); let mut yo = Txn::new(); + let mut new = HashMap::new(); for txn_op in txn.iter() { let op = txn_op.op.as_str(); match op { @@ -57,7 +58,7 @@ impl TANode { out.push(op); } "w" => { - self.store.insert(txn_op.key, txn_op.value.unwrap()); + new.insert(txn_op.key, txn_op.value.unwrap()); yo.push(txn_op.clone()); out.push(txn_op.clone()); } @@ -67,13 +68,13 @@ impl TANode { } } - (out, yo) - } - - fn handle_yo(&mut self, txn: &Txn) { - for op in txn.iter() { - self.store.insert(op.key, op.value.unwrap()); + // if the transaction were aborted, we'd not want to commit it by inserting from + // `new` here + for (k, v) in new.into_iter() { + self.store.insert(k, v); } + + (out, yo) } } @@ -86,15 +87,26 @@ impl Node for TANode { let txn = get_txn(&msg); let (txn, yo) = self.transact(&txn); + // simulated aborted transaction for G1a-resistance + if txn.is_empty() { + let mut error = Body::from_type("error"); + let ec = + ErrorCode::Definite(nebkor_maelstrom::protocol::DefiniteError::TxnConflict); + error.code = Some(ec); + error.text = Some("shit's fucked".into()); + runner.reply(&msg, error); + return; + } gossip(runner, &yo); let payload = mk_payload(&[("txn", txn.serialize())]); let body = Body::from_type("txn_ok").with_payload(payload); runner.reply(&msg, body); } - "yo" => { let txn = get_txn(&msg); - self.handle_yo(&txn); + for op in txn.iter() { + self.store.insert(op.key, op.value.unwrap()); + } } _ => { eprintln!("unknown message type {typ}")