feat: Hook up tx_field host function

This commit is contained in:
TimothyBanks
2026-08-10 16:40:51 -04:00
parent 3a2cf64a69
commit 1656a19fe6
11 changed files with 106 additions and 1 deletions

View File

@@ -135,6 +135,12 @@ host_functions! {
#[wasm_name = "cache_le"]
fn cache_ledger_obj(&self, obj_id: &[u8], cache_idx: i32) -> HostResult<i32>;
/// The serialized bytes of one field of the transaction being executed, selected
/// by its `SField` code.
#[gas = 70]
#[wasm_name = "tx_field"]
fn get_tx_field(&self, field: i32, out: &mut [u8]) -> HostResult<usize>;
/// The serialized bytes of one field of the current (escrow) ledger object.
#[gas = 70]
#[wasm_name = "home_le_field"]

View File

@@ -53,6 +53,14 @@ impl HostFunctions for FakeHost {
Ok(if cache_idx == 0 { 1 } else { cache_idx })
}
/// A field getter over the transaction; fails on a negative selector.
fn get_tx_field(&self, field: i32, out: &mut [u8]) -> HostResult<usize> {
if field < 0 {
return Err(HostError::FieldNotFound);
}
put(out, &[field as u8])
}
/// Fails on a field it doesn't know, so the error channel is exercised too.
fn get_current_ledger_obj_field(&self, field: i32, out: &mut [u8]) -> HostResult<usize> {
if field < 0 {
@@ -97,6 +105,8 @@ fn the_trait_is_implementable() {
assert_eq!(host.is_amendment_enabled(&[]), Ok(0));
assert_eq!(host.cache_ledger_obj(&[1; 32], 0), Ok(1));
assert_eq!(host.cache_ledger_obj(&[1; 32], 5), Ok(5));
assert_eq!(host.get_tx_field(5, &mut out), Ok(1));
assert_eq!(out[0], 5);
assert_eq!(host.get_current_ledger_obj_field(3, &mut out), Ok(1));
assert_eq!(out[0], 3);
assert_eq!(host.sha512_half(b"abc", &mut out), Ok(HASH_LEN));
@@ -172,6 +182,7 @@ fn the_spec_table_matches_the_declarations() {
("base_fee", 60),
("amendment_enabled", 100),
("cache_le", 5000),
("tx_field", 70),
("home_le_field", 70),
("sha512_half", 2000),
("trace", 500),

View File

@@ -183,6 +183,10 @@ mod ffi {
#[cxx_name = "cacheLedgerObj"]
fn cache_ledger_obj(self: &HostContext, obj_id: &[u8], cache_idx: i32) -> i32;
#[namespace = "xrpl"]
#[cxx_name = "getTxField"]
fn get_tx_field(self: &HostContext, field: i32, out: &mut [u8]) -> i32;
#[namespace = "xrpl"]
#[cxx_name = "getCurrentLedgerObjField"]
fn get_current_ledger_obj_field(self: &HostContext, field: i32, out: &mut [u8]) -> i32;
@@ -265,6 +269,10 @@ impl HostFunctions for CxxHost<'_> {
scalar(self.ctx.cache_ledger_obj(obj_id, cache_idx))
}
fn get_tx_field(&self, field: i32, out: &mut [u8]) -> HostResult<usize> {
bytes_written(self.ctx.get_tx_field(field, out))
}
fn get_current_ledger_obj_field(&self, field: i32, out: &mut [u8]) -> HostResult<usize> {
bytes_written(self.ctx.get_current_ledger_obj_field(field, out))
}

View File

@@ -203,6 +203,9 @@ mod tests {
fn cache_ledger_obj(&self, _obj_id: &[u8], _cache_idx: i32) -> HostResult<i32> {
unreachable!("no unit test in this module calls the host")
}
fn get_tx_field(&self, _field: i32, _out: &mut [u8]) -> HostResult<usize> {
unreachable!("no unit test in this module calls the host")
}
fn get_current_ledger_obj_field(&self, _field: i32, _out: &mut [u8]) -> HostResult<usize> {
unreachable!("no unit test in this module calls the host")
}

View File

@@ -103,6 +103,20 @@ pub(crate) fn register_host_functions(
})
},
),
HostFunctionSpec::GetTxField => linker.func_wrap(
HOST_MODULE,
op.wasm_name(),
|mut caller: Caller<'_, VmState<'_>>,
field: i32,
out_ptr: i32,
out_len: i32|
-> Result<i32, wasmi::Error> {
charged(&mut caller, HostFunctionSpec::GetTxField, |c| {
let out = Region::new(out_ptr, out_len);
write_into(c, out, |host, out| host.get_tx_field(field, out))
})
},
),
HostFunctionSpec::GetCurrentLedgerObjField => linker.func_wrap(
HOST_MODULE,
op.wasm_name(),

View File

@@ -81,6 +81,11 @@ fn call_for(op: HostFunctionSpec) -> Call {
"(call $cache_le (i32.const 0) (i32.const 32) (i32.const 0))",
3,
),
HostFunctionSpec::GetTxField => (
import::TX_FIELD,
"(call $tx_field (i32.const 1) (i32.const 0) (i32.const 4))",
3,
),
HostFunctionSpec::GetCurrentLedgerObjField => (
import::HOME_LE_FIELD,
"(call $home_le_field (i32.const 1) (i32.const 0) (i32.const 4))",

View File

@@ -156,6 +156,21 @@ fn the_output_region_is_the_pointer_the_guest_gave() {
}
}
/// A field getter over the transaction: the selector reaches the host, and the bytes
/// it answers land where the guest asked. It has its own answer set, distinct from
/// the current-object field getter's.
#[test]
fn tx_field_passes_the_selector_and_writes_the_field() {
let host = FakeHost::new().answering_tx_field(17, support::Answer::bytes([0xab, 0xcd]));
let wat = module(
&[import::TX_FIELD, ONE_PAGE],
"(call $tx_field (i32.const 17) (i32.const 0) (i32.const 64))",
);
assert_eq!(status(&wat, &host), 2);
assert_eq!(*host.tx_fields_asked.borrow(), vec![17]);
}
/// A leading scalar parameter reaches the host as declared.
#[test]
fn home_le_field_passes_the_field_selector_through() {

View File

@@ -98,13 +98,14 @@ fn a_disabled_feature_does_not_pass() {
/// Every host function the ABI declares, spelled as a guest imports it. The count
/// is asserted against the ABI so a function added to it cannot be left out here.
const ALL_IMPORTS: [&str; 10] = [
const ALL_IMPORTS: [&str; 11] = [
import::LDGR_INDEX,
import::PARENT_LDGR_TIME,
import::PARENT_LDGR_HASH,
import::BASE_FEE,
import::AMENDMENT_ENABLED,
import::CACHE_LE,
import::TX_FIELD,
import::HOME_LE_FIELD,
import::SHA512_HALF,
import::TRACE,

View File

@@ -117,6 +117,11 @@ pub struct FakeHost {
pub cache_slot: HostResult<i32>,
/// Every (object id, requested slot) `cache_ledger_obj` was asked to cache.
pub cached: RefCell<Vec<(Vec<u8>, i32)>>,
/// What `get_tx_field` answers, by field selector. An unlisted selector answers
/// `FieldNotFound`.
pub tx_fields: HashMap<i32, Answer>,
/// Every field selector `get_tx_field` was asked for.
pub tx_fields_asked: RefCell<Vec<i32>>,
/// What `get_current_ledger_obj_field` answers, by field selector. An
/// unlisted selector answers `FieldNotFound`.
pub fields: HashMap<i32, Answer>,
@@ -148,6 +153,8 @@ impl Default for FakeHost {
// Slot 1 by default; slot assignment is the host's job, not the ABI's.
cache_slot: Ok(1),
cached: RefCell::new(Vec::new()),
tx_fields: HashMap::new(),
tx_fields_asked: RefCell::new(Vec::new()),
fields: HashMap::new(),
digest: Answer::filler(32),
fields_asked: RefCell::new(Vec::new()),
@@ -192,6 +199,11 @@ impl FakeHost {
self
}
pub fn answering_tx_field(mut self, field: i32, answer: Answer) -> FakeHost {
self.tx_fields.insert(field, answer);
self
}
pub fn answering_field(mut self, field: i32, answer: Answer) -> FakeHost {
self.fields.insert(field, answer);
self
@@ -234,6 +246,14 @@ impl HostFunctions for FakeHost {
self.cache_slot
}
fn get_tx_field(&self, field: i32, out: &mut [u8]) -> HostResult<usize> {
self.tx_fields_asked.borrow_mut().push(field);
match self.tx_fields.get(&field) {
Some(answer) => answer.fill(out),
None => Err(HostError::FieldNotFound),
}
}
fn get_current_ledger_obj_field(&self, field: i32, out: &mut [u8]) -> HostResult<usize> {
self.fields_asked.borrow_mut().push(field);
match self.fields.get(&field) {
@@ -282,6 +302,8 @@ pub mod import {
pub const AMENDMENT_ENABLED: &str = r#"(import "host_lib" "amendment_enabled" (func $amendment_enabled (param i32 i32) (result i32)))"#;
pub const CACHE_LE: &str =
r#"(import "host_lib" "cache_le" (func $cache_le (param i32 i32 i32) (result i32)))"#;
pub const TX_FIELD: &str =
r#"(import "host_lib" "tx_field" (func $tx_field (param i32 i32 i32) (result i32)))"#;
pub const HOME_LE_FIELD: &str = r#"(import "host_lib" "home_le_field" (func $home_le_field (param i32 i32 i32) (result i32)))"#;
pub const SHA512_HALF: &str = r#"(import "host_lib" "sha512_half" (func $sha512_half (param i32 i32 i32 i32) (result i32)))"#;
pub const TRACE: &str =

View File

@@ -65,6 +65,9 @@ public:
[[nodiscard]] std::int32_t
cacheLedgerObj(rust::Slice<std::uint8_t const> objId, std::int32_t cacheIdx) const noexcept;
[[nodiscard]] std::int32_t
getTxField(std::int32_t field, rust::Slice<std::uint8_t> out) const noexcept;
[[nodiscard]] std::int32_t
getCurrentLedgerObjField(std::int32_t field, rust::Slice<std::uint8_t> out) const noexcept;

View File

@@ -151,6 +151,23 @@ HostContext::cacheLedgerObj(rust::Slice<std::uint8_t const> objId, std::int32_t
});
}
std::int32_t
HostContext::getTxField(std::int32_t field, rust::Slice<std::uint8_t> out) const noexcept
{
return guarded(hostFunctions_.getJournal(), kHostInternal, [&] {
auto const& knownSFields = SField::getKnownCodeToField();
auto const it = knownSFields.find(field);
if (it == knownSFields.end())
return hfErrorToInt(HostFunctionError::InvalidField);
auto const value = hostFunctions_.getTxField(*it->second);
if (!value)
return hfErrorToInt(value.error());
return answer(out, value->data(), value->size());
});
}
std::int32_t
HostContext::getCurrentLedgerObjField(std::int32_t field, rust::Slice<std::uint8_t> out)
const noexcept