Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 94 additions & 5 deletions crates/tinywallet-web3/src/crypto/chains/solana/mod_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -396,9 +396,9 @@ async fn a_versioned_transaction_gets_our_signature_in_our_slot() {
let signature = ed25519_dalek::Signature::from_slice(&sent[1..65]).unwrap();
FakeSigner::solana_key()
.verifying_key()
.verify(&wire[65..], &signature)
.expect("the message bytes were signed");
assert_eq!(&sent[65..], &wire[65..], "the message is untouched");
.verify(&sent[65..], &signature)
.expect("the message bytes that were sent were signed");
assert_eq!(&sent[..1], &wire[..1], "one signature slot, as built");
}

#[tokio::test]
Expand Down Expand Up @@ -448,13 +448,97 @@ async fn a_v0_message_is_signed_with_its_version_prefix_included() {
SignerCall::Message(_, m) => Some(m),
_ => None,
});
let message_signed = message_signed.unwrap();
assert_eq!(message_signed[0], 0x80, "the version prefix is signed");
assert_eq!(
message_signed.unwrap(),
wire[65..].to_vec(),
message_signed,
broadcast_wire(&rig)[65..].to_vec(),
"the version prefix is part of what is signed"
);
}

/// A v0 transaction shaped like deBridge's `tx.data`: one empty signature
/// slot, the `0x80` version prefix, `signer` as the fee payer, and the
/// all-zero placeholder blockhash deBridge leaves for the signer to fill.
fn unsigned_v0_placeholder(signer: &[u8; 32]) -> Vec<u8> {
let mut wire = unsigned_legacy(signer);
wire.insert(1 + 64, 0x80);
wire.extend(encode_shortvec(0)); // address table lookups
wire
}

/// Where the recent blockhash sits in [`unsigned_v0_placeholder`]: the
/// signature slot, the version prefix, the header, one key.
const V0_BLOCKHASH: std::ops::Range<usize> = 1 + 64 + 1 + 3 + 1 + 32..1 + 64 + 1 + 3 + 1 + 64;

#[tokio::test]
async fn a_debridge_placeholder_blockhash_is_replaced_with_a_fresh_one_before_signing() {
let rig = Rig::new();
script_node(&rig);
let signer = b58_to_pubkey(sample_address(WalletChain::Solana)).unwrap();
let wire = unsigned_v0_placeholder(&signer);
assert_eq!(&wire[V0_BLOCKHASH], &[0u8; 32], "deBridge's placeholder");

sign_and_broadcast_versioned(&rig.engine, &format!("0x{}", hex::encode(&wire)))
.await
.unwrap();

let methods: Vec<String> = rig
.transport
.rpc_calls()
.into_iter()
.map(|(m, _)| m)
.collect();
assert_eq!(methods, ["getLatestBlockhash", "sendTransaction"]);

let sent = broadcast_wire(&rig);
assert_eq!(
&sent[V0_BLOCKHASH],
&b58_to_pubkey(BLOCKHASH).unwrap(),
"the node's blockhash replaced the placeholder"
);
let mut expected = wire.clone();
expected[V0_BLOCKHASH].copy_from_slice(&b58_to_pubkey(BLOCKHASH).unwrap());
assert_eq!(&sent[65..], &expected[65..], "only the blockhash changed");
let signature = ed25519_dalek::Signature::from_slice(&sent[1..65]).unwrap();
FakeSigner::solana_key()
.verifying_key()
.verify(&sent[65..], &signature)
.expect("the signature covers the refreshed message");
}

#[tokio::test]
async fn a_transaction_another_party_already_signed_keeps_its_blockhash() {
let rig = Rig::new();
script_node(&rig);
let signer = b58_to_pubkey(sample_address(WalletChain::Solana)).unwrap();
// Two signers: a co-signer that has already signed, then us.
let mut message = Vec::new();
message.extend([2u8, 0u8, 0u8]);
message.extend(encode_shortvec(2));
message.extend([9u8; 32]);
message.extend(signer);
message.extend([5u8; 32]);
message.extend(encode_shortvec(0));
let mut wire = Vec::new();
wire.extend(encode_shortvec(2));
wire.extend([3u8; 64]);
wire.extend([0u8; 64]);
wire.extend(&message);

sign_and_broadcast_versioned(&rig.engine, &hex::encode(&wire))
.await
.unwrap();

assert!(
rig.transport.first_rpc("getLatestBlockhash").is_none(),
"a refreshed blockhash would void the co-signer's signature"
);
let sent = broadcast_wire(&rig);
assert_eq!(&sent[..65], &wire[..65], "the co-signature is kept");
assert_eq!(&sent[129..], &wire[129..], "the message is untouched");
}

#[tokio::test]
async fn malformed_versioned_blobs_are_rejected_with_specific_messages() {
let rig = Rig::new();
Expand Down Expand Up @@ -488,6 +572,11 @@ async fn malformed_versioned_blobs_are_rejected_with_specific_messages() {
hex::encode(&good[..65 + 3 + 1 + 10]),
"Solana account keys region truncated",
),
// Keys present, recent blockhash cut short.
(
hex::encode(&good[..65 + 3 + 1 + 32 + 10]),
"Solana recent blockhash truncated",
),
];
for (blob, expected) in cases {
let err = sign_and_broadcast_versioned(&rig.engine, &blob)
Expand Down
27 changes: 26 additions & 1 deletion crates/tinywallet-web3/src/crypto/chains/solana/versioned.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,22 @@
//! signature slot whose account key equals the wallet's pubkey is filled by
//! signing the full message bytes (legacy or v0: the slice includes the v0
//! version prefix, which is what Solana signs).
//!
//! deBridge builds its Solana transactions with a placeholder recent blockhash
//! (all zeros) and expects the signer to put a fresh one in before signing
//! ("Update blockhash!" in its order-submission guide); sent as built, every
//! one fails preflight with `BlockhashNotFound`. So when no one has signed yet,
//! the blockhash is replaced with the node's latest before our signature is
//! made. A transaction another party has already signed keeps its blockhash:
//! changing it would void their signature.

use log::debug;

use crate::crypto::execution::RawBroadcastResult;
use crate::crypto::wallet::{WalletChain, WalletEngine};

use super::wire::{decode_shortvec, pubkey_to_b58};
use super::{LOG_PREFIX, broadcast_solana, signer_pubkey, solana_sign};
use super::{LOG_PREFIX, broadcast_solana, fetch_recent_blockhash, signer_pubkey, solana_sign};

/// Where the signer keys and message sit inside a transaction blob.
struct Layout {
Expand All @@ -27,6 +35,8 @@ struct Layout {
keys_start: usize,
/// How many leading account keys are signers and present in the blob.
signer_keys: usize,
/// Offset of the recent blockhash within the message.
blockhash_start: usize,
}

/// Parse just enough of `wire` to find the signer keys.
Expand Down Expand Up @@ -61,12 +71,17 @@ fn parse_layout(wire: &[u8]) -> Result<Layout, String> {
if keys_start + signer_keys * 32 > message.len() {
return Err("Solana account keys region truncated".to_string());
}
let blockhash_start = keys_start + usize::from(account_count) * 32;
if blockhash_start + 32 > message.len() {
return Err("Solana recent blockhash truncated".to_string());
}
Ok(Layout {
sigs_start,
num_signatures,
message_start,
keys_start,
signer_keys,
blockhash_start,
})
}

Expand Down Expand Up @@ -99,7 +114,17 @@ pub(crate) async fn sign_and_broadcast_versioned(
return Err("Solana signer index exceeds signature slot count".to_string());
}

// Nobody has signed yet: the blockhash is ours to set, and must be fresh.
let signatures = &wire[layout.sigs_start..layout.message_start];
if signatures.iter().all(|byte| *byte == 0) {
let blockhash = fetch_recent_blockhash(engine).await?;
let off = layout.message_start + layout.blockhash_start;
wire[off..off + 32].copy_from_slice(&blockhash);
debug!("{LOG_PREFIX} sign_and_broadcast_versioned refreshed the recent blockhash");
}

// Sign the message bytes and write into our signature slot.
let message = &wire[layout.message_start..];
let sig_bytes = solana_sign(engine, message).await?;
let slot_off = layout.sigs_start + our_index * 64;
wire[slot_off..slot_off + 64].copy_from_slice(&sig_bytes);
Expand Down
Loading