Skip to content

Commit

Permalink
define Address as u128
Browse files Browse the repository at this point in the history
  • Loading branch information
Centril committed Aug 20, 2024
1 parent 2a9ae03 commit 89bfb29
Show file tree
Hide file tree
Showing 16 changed files with 105 additions and 115 deletions.
39 changes: 16 additions & 23 deletions crates/bindings-csharp/BSATN.Runtime/Builtins.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,44 +61,37 @@ string wrapperPropertyName
);
}

public record Address : BytesWrapper
public struct Address
{
protected override int SIZE => 16;
private readonly U128 value;

public Address() { }

private Address(byte[] bytes)
: base(bytes) { }

public static Address? From(byte[] bytes)
{
if (bytes.All(b => b == 0))
public Address(U128 v) => value = v;
public static Address? From(ulong upper, ulong lower) {
if (upper == 0 && lower == 0)
{
return null;
}
return new(bytes);
}

public static Address Random()
{
var random = new Random();
var addr = new Address();
random.NextBytes(addr.bytes);
return addr;
else
{
return new Address(new U128(upper, lower));
}
}

public readonly struct BSATN : IReadWrite<Address>
{
public Address Read(BinaryReader reader) => new(ReadRaw(reader));
public Address Read(BinaryReader reader) => new(new SpacetimeDB.BSATN.U128Stdb().Read(reader));

public void Write(BinaryWriter writer, Address value) => value.Write(writer);
public void Write(BinaryWriter writer, Address value)
=> new SpacetimeDB.BSATN.U128Stdb().Write(writer, value.value);

public AlgebraicType GetAlgebraicType(ITypeRegistrar registrar) =>
BytesWrapper.GetAlgebraicType(registrar, "__address_bytes");
new AlgebraicType.Product(
[new("__address__", new AlgebraicType.U128(default))]
);
}

// This must be explicitly forwarded to base, otherwise record will generate a new implementation.
public override string ToString() => base.ToString();
public override string ToString() => value.ToString();
}

public record Identity : BytesWrapper
Expand Down
2 changes: 1 addition & 1 deletion crates/bindings-csharp/Runtime/Internal/Module.cs
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,7 @@ BytesSink error
var sender = Identity.From(MemoryMarshal.AsBytes([sender_0, sender_1, sender_2, sender_3]).ToArray());

// Piece together the sender address.
var address = Address.From(MemoryMarshal.AsBytes([address_0, address_1]).ToArray());
var address = Address.From(address_1, address_0);

try
{
Expand Down
2 changes: 1 addition & 1 deletion crates/bindings/src/rt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -414,7 +414,7 @@ extern "C" fn __describe_module__(description: BytesSink) {
/// - `sender_3` contains bytes `[24..32]`.
///
/// The `address_{0-1}` are the pieces of a `[u8; 16]` (`u128`) representing the callers's `Address`.
/// They are encoded as follows (assuming `identity.__address_bytes: [u8; 16]`):
/// They are encoded as follows (assuming `address.__address__: u128`):
/// - `address_0` contains bytes `[0 ..8 ]`.
/// - `address_1` contains bytes `[8 ..16]`.
///
Expand Down
2 changes: 1 addition & 1 deletion crates/core/src/client/messages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,7 @@ impl<U: ToProtocol<Encoded = ws::DatabaseUpdate>> ToProtocol for TransactionUpda
},
energy_quanta_used: event.energy_quanta_used,
host_execution_duration_micros: event.host_execution_duration.as_micros() as u64,
caller_address: event.caller_address.unwrap_or(Address::zero()),
caller_address: event.caller_address.unwrap_or(Address::ZERO),
};

ws::ServerMessage::TransactionUpdate(tx_update)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1044,7 +1044,7 @@ mod tests {
}

fn get_datastore() -> Result<Locking> {
Locking::bootstrap(Address::zero())
Locking::bootstrap(Address::ZERO)
}

fn col(col: u16) -> ColList {
Expand Down Expand Up @@ -1352,14 +1352,14 @@ mod tests {
ColRow { table: ST_CONSTRAINT_ID.into(), pos: 3, name: "table_id", ty: TableId::get_type() },
ColRow { table: ST_CONSTRAINT_ID.into(), pos: 4, name: "columns", ty: AlgebraicType::array(ColId::get_type()) },

ColRow { table: ST_MODULE_ID.into(), pos: 0, name: "database_address", ty: AlgebraicType::bytes() },
ColRow { table: ST_MODULE_ID.into(), pos: 0, name: "database_address", ty: AlgebraicType::U128 },
ColRow { table: ST_MODULE_ID.into(), pos: 1, name: "owner_identity", ty: AlgebraicType::bytes() },
ColRow { table: ST_MODULE_ID.into(), pos: 2, name: "program_kind", ty: AlgebraicType::U8 },
ColRow { table: ST_MODULE_ID.into(), pos: 3, name: "program_hash", ty: AlgebraicType::bytes() },
ColRow { table: ST_MODULE_ID.into(), pos: 4, name: "program_bytes", ty: AlgebraicType::bytes() },

ColRow { table: ST_CLIENT_ID.into(), pos: 0, name: "identity", ty: AlgebraicType::bytes()},
ColRow { table: ST_CLIENT_ID.into(), pos: 1, name: "address", ty: AlgebraicType::bytes()},
ColRow { table: ST_CLIENT_ID.into(), pos: 1, name: "address", ty: AlgebraicType::U128},

ColRow { table: ST_VAR_ID.into(), pos: 0, name: "name", ty: AlgebraicType::String },
ColRow { table: ST_VAR_ID.into(), pos: 1, name: "value", ty: StVarValue::type_of() },
Expand Down
15 changes: 8 additions & 7 deletions crates/core/src/db/datastore/system_tables.rs
Original file line number Diff line number Diff line change
Expand Up @@ -386,7 +386,7 @@ pub(crate) fn st_module_schema() -> TableSchema {
RawTableDefV8::new(
ST_MODULE_NAME.into(),
vec![
RawColumnDefV8::sys(StModuleFields::DatabaseAddress.name(), AlgebraicType::bytes()),
RawColumnDefV8::sys(StModuleFields::DatabaseAddress.name(), AlgebraicType::U128),
RawColumnDefV8::sys(StModuleFields::OwnerIdentity.name(), AlgebraicType::bytes()),
RawColumnDefV8::sys(StModuleFields::ProgramKind.name(), AlgebraicType::U8),
RawColumnDefV8::sys(StModuleFields::ProgramHash.name(), AlgebraicType::bytes()),
Expand All @@ -401,15 +401,15 @@ pub(crate) fn st_module_schema() -> TableSchema {
///
// identity | address
// -----------------------------------------------------------------------------------------+--------------------------------------------------------
// (__identity_bytes = 0x7452047061ea2502003412941d85a42f89b0702588b823ab55fc4f12e9ea8363) | (__address_bytes = 0x6bdea3ab517f5857dc9b1b5fe99e1b14)
// (__identity_bytes = 0x7452047061ea2502003412941d85a42f89b0702588b823ab55fc4f12e9ea8363) | (__address__ = 0x6bdea3ab517f5857dc9b1b5fe99e1b14)
fn st_client_schema() -> TableSchema {
TableSchema::from_def(
ST_CLIENT_ID,
RawTableDefV8::new(
ST_CLIENT_NAME.into(),
vec![
RawColumnDefV8::sys(StClientFields::Identity.name(), AlgebraicType::bytes()),
RawColumnDefV8::sys(StClientFields::Address.name(), AlgebraicType::bytes()),
RawColumnDefV8::sys(StClientFields::Address.name(), AlgebraicType::U128),
],
)
.with_type(StTableType::System)
Expand Down Expand Up @@ -794,9 +794,10 @@ pub fn read_bytes_from_col(row: RowRef<'_>, col: impl StFields) -> Result<Box<[u

/// Read an [`Address`] directly from the column `col` in `row`.
///
/// The [`Address`] is assumed to be stored as a flat byte array.
/// The [`Address`] is assumed to be stored as an u128.
pub fn read_addr_from_col(row: RowRef<'_>, col: impl StFields) -> Result<Address, DBError> {
read_bytes_from_col(row, col).map(Address::from_slice)
let val: u128 = row.read_col(col.col_id())?;
Ok(val.into())
}

/// Read an [`Identity`] directly from the column `col` in `row`.
Expand Down Expand Up @@ -838,7 +839,7 @@ impl From<StModuleRow> for ProductValue {
}: StModuleRow,
) -> Self {
product![
database_address.as_slice().as_slice(),
database_address.to_u128(),
owner_identity.as_bytes().as_slice(),
program_kind,
program_hash.as_slice(),
Expand All @@ -855,7 +856,7 @@ pub struct StClientsRow {

impl From<&StClientsRow> for ProductValue {
fn from(x: &StClientsRow) -> Self {
product![x.identity.as_bytes().as_slice(), x.address.as_slice().as_slice()]
product![x.identity.as_bytes().as_slice(), x.address.to_u128()]
}
}

Expand Down
2 changes: 1 addition & 1 deletion crates/core/src/host/wasmtime/wasmtime_module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ impl module_host_actor::WasmInstance for WasmtimeInstance {

// Prepare sender identity and address.
let [sender_0, sender_1, sender_2, sender_3] = bytemuck::must_cast(*op.caller_identity.as_bytes());
let [address_0, address_1] = bytemuck::must_cast(*op.caller_address.as_slice());
let [address_0, address_1] = bytemuck::must_cast(op.caller_address.as_byte_array());

// Prepare arguments to the reducer + the error sink & start timings.
let (args_source, errors_sink) = store.data_mut().start_reducer(op.name, op.arg_bytes);
Expand Down
12 changes: 4 additions & 8 deletions crates/core/src/sql/compiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -236,8 +236,7 @@ mod tests {
use spacetimedb_lib::{Address, Identity};
use spacetimedb_primitives::{col_list, ColList, TableId};
use spacetimedb_sats::{
product, satn, AlgebraicType, AlgebraicValue, GroundSpacetimeType as _, ProductType, ProductTypeElement,
Typespace, ValueWithType,
product, satn, AlgebraicType, AlgebraicValue, GroundSpacetimeType as _, ProductType, Typespace, ValueWithType,
};
use spacetimedb_vm::expr::{ColumnOp, IndexJoin, IndexScan, JoinExpr, Query};
use std::convert::From;
Expand Down Expand Up @@ -398,10 +397,7 @@ mod tests {
#[test]
fn output_identity_address() -> ResultTest<()> {
let row = product![AlgebraicValue::from(Identity::__dummy())];
let kind = ProductType::new(Box::new([ProductTypeElement::new(
Identity::get_type(),
Some("i".into()),
)]));
let kind: ProductType = [("i", Identity::get_type())].into();
let ty = Typespace::EMPTY.with_type(&kind);
let out = ty
.with_values(&row)
Expand All @@ -426,7 +422,7 @@ mod tests {
AlgebraicValue::String("a".into()),
AlgebraicValue::Bytes((*Identity::ZERO.as_bytes()).into()),
AlgebraicValue::Bytes((*Identity::ZERO.as_bytes()).into()),
AlgebraicValue::Bytes((*Address::__DUMMY.as_slice()).into()),
Address::__DUMMY.to_u128().into(),
]);

assert_eq!(
Expand All @@ -441,7 +437,7 @@ mod tests {
AlgebraicValue::String("a".into()),
AlgebraicValue::Bytes((*Identity::ZERO.as_bytes()).into()),
AlgebraicValue::product([AlgebraicValue::Bytes((*Identity::ZERO.as_bytes()).into())]),
AlgebraicValue::product([AlgebraicValue::Bytes((*Address::__DUMMY.as_slice()).into())]),
AlgebraicValue::product([Address::__DUMMY.to_u128().into()]),
];

let value = ValueWithType::new(ty, &value);
Expand Down
6 changes: 4 additions & 2 deletions crates/core/src/sql/type_check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,9 @@ fn resolve_type(field: &FieldExpr, ty: AlgebraicType) -> Result<Option<Algebraic
}

if let (AlgebraicType::Product(_), FieldExpr::Value(val)) = (&ty, field) {
if val.as_bytes().is_some() {
if val.as_u128().is_some() {
return Ok(Some(AlgebraicType::U128));
} else if val.as_bytes().is_some() {
return Ok(Some(AlgebraicType::bytes()));
}
}
Expand Down Expand Up @@ -146,7 +148,7 @@ fn check_both(op: OpQuery, lhs: &Typed, rhs: &Typed) -> Result<(), PlanError> {
fn patch_type(lhs: &FieldOp, ty_lhs: &mut Typed, ty_rhs: &Typed) -> Result<(), PlanError> {
if let FieldOp::Field(lhs_field) = lhs {
if let Some(ty) = ty_rhs.ty() {
if ty.is_sum() || ty.as_product().map_or(false, |x| x.is_special()) {
if ty.is_sum() || ty.as_product().is_some_and(|x| x.is_special()) {
ty_lhs.set_ty(resolve_type(lhs_field, ty.clone())?);
}
}
Expand Down
Loading

0 comments on commit 89bfb29

Please sign in to comment.