thruput-xdr 0.68.0

Bindings for Thruput protocol structures
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
// Generated by xdrc 0.18.0 (xdrs d7777c37264da66eb41f8139bd539c4aa049fcc5). Do not edit.

#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(non_upper_case_globals)]
#![allow(unused_imports)]
#![allow(dead_code)]
#![allow(unused_variables)]
#![allow(clippy::unnecessary_cast)]
use crate::*;
use core::ops::{Deref, DerefMut};
use core::option::Option;
#[cfg(feature = "std")]
use std::io::{Read, Write};
#[cfg(feature = "xdrs")]
use xdrs::*;
#[cfg(feature = "serde")]
use ::serde::{Deserialize, Serialize};

//==============================================================================
// Contracts and Contract Deployment
//
// This module defines the contract abstraction in Thruput. Contracts are
// code that can be deployed to addresses and invoked to execute logic.
//
// Key concepts:
// - Contracts can be executable blobs, native precompiled code, or test mocks
// - Contract addresses are deterministically derived from deployment parameters
// - Contract methods are identified by 8-byte entrypoint IDs
// - Entrypoint IDs are derived from interface names and versions
//==============================================================================
//------------------------------------------------------------------------------
// Contract Types and Code
//------------------------------------------------------------------------------
/// The largest contract code blob a chain admits when its configuration does
/// not state `kConfigParamMaxContractSizeBytes`. Includes the artifact header,
/// code, and initial memory.
pub const kDefaultMaxContractSizeBytes: u32 = 524288;

/// An opaque blob of executable code.
///
/// This is the raw binary that will be executed as an RV32 contract.
///
/// Unbounded on the wire: the size a chain admits is a configuration
/// parameter (`kConfigParamMaxContractSizeBytes`), enforced where a
/// transaction attaches a contract rather than where one is decoded.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "xdrs", derive(ReadXDR, WriteXDR, ConstXDRSize))]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(C)]
pub struct ContractBlob {
    pub data: BytesM,
}

/// What an RV32 artifact extension carries. Values are permanent: a value is
/// never reused.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "xdrs", derive(ReadXDR, WriteXDR, ConstXDRSize))]
#[cfg_attr(feature = "serde", serde(transparent))]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[derive(Copy)]
#[repr(transparent)]
pub struct Rv32ArtifactExtensionKind(pub i32);

impl Rv32ArtifactExtensionKind {
    /// The body is an `Rv32ContractSpecExtension`.
    pub const kRv32ExtensionContractSpec: Self = Self(1);
}

impl From<i32> for Rv32ArtifactExtensionKind {
    fn from(v: i32) -> Self {
        Self(v)
    }
}

#[cfg(feature = "xdrs")]
impl xdrs::XDRDiscriminant for Rv32ArtifactExtensionKind {
    const ENCODING: xdrs::DiscriminantEncoding = xdrs::DiscriminantEncoding::Signed;
    fn discriminant(&self) -> i32 {
        self.0
    }
    fn from_discriminant(d: i32) -> Self {
        Self(d)
    }
}

#[cfg(feature = "std")]
impl core::fmt::Display for Rv32ArtifactExtensionKind {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self.0 {
            x if x == Self::kRv32ExtensionContractSpec.0 => {
                f.write_str("Rv32ArtifactExtensionKind::kRv32ExtensionContractSpec")
            }
            _ => write!(f, "Rv32ArtifactExtensionKind({})", self.0),
        }
    }
}

/// One extension in a v6 RV32 artifact: data after initial memory that the
/// runtime never loads into guest memory.
///
/// `kind` is an `Rv32ArtifactExtensionKind`, typed as `unsigned int` so a
/// decoder accepts kinds it does not know. Zero is reserved. The chain stores
/// `body` without interpreting it.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "xdrs", derive(ReadXDR, WriteXDR, ConstXDRSize))]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(C)]
pub struct Rv32ArtifactExtension {
    pub kind: u32,
    pub body: BytesM,
}

/// The extension list that ends a v6 RV32 artifact, running from the end of
/// initial memory exactly to the end of the artifact.
///
/// Kinds are strictly ascending, so there is at most one extension of each
/// kind and exactly one encoding of any set of extensions. The chain checks
/// only this framing; adding a kind needs no runtime change.
pub type Rv32ArtifactExtensions = VecM<Rv32ArtifactExtension>;

/// The body of a `kRv32ExtensionContractSpec` extension.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "xdrs", derive(ReadXDR, WriteXDR, ConstXDRSize))]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(C)]
pub struct Rv32ContractSpecExtension {
    /// Schema of `spec`. 1: `spec` is an XDR `ContractSpec` (contract_spec.x).
    pub schema_version: u32,
    pub spec: BytesM,
}

/// The execution environment for a contract.
///
/// Discriminant 0 is retired. It selected an earlier contract runtime, which
/// was removed once RV32 became the only deployable execution environment.
/// Do not reuse the value: old encodings that carry it must fail to parse
/// rather than silently decode as a live contract type.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "xdrs", derive(ReadXDR, WriteXDR, ConstXDRSize))]
#[cfg_attr(feature = "serde", serde(transparent))]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[derive(Copy)]
#[repr(transparent)]
pub struct ContractType(pub i32);

impl ContractType {
    /// Precompiled native contract implemented natively by the node.
    ///
    /// Used for system contracts like the native token.
    /// Cheaper to invoke than a deployed RV32 contract, but users cannot
    /// deploy new ones.
    pub const kNative: Self = Self(1);
    /// Mock contract for local testing.
    ///
    /// Never deployed on-chain; exists only in the test harness.
    pub const kMockTest: Self = Self(2);
    /// RiscV contract executed in the RV32 VM.
    ///
    /// This is the standard contract type for user-deployed contracts.
    pub const kRv32: Self = Self(3);
}

impl From<i32> for ContractType {
    fn from(v: i32) -> Self {
        Self(v)
    }
}

#[cfg(feature = "xdrs")]
impl xdrs::XDRDiscriminant for ContractType {
    const ENCODING: xdrs::DiscriminantEncoding = xdrs::DiscriminantEncoding::Signed;
    fn discriminant(&self) -> i32 {
        self.0
    }
    fn from_discriminant(d: i32) -> Self {
        Self(d)
    }
}

#[cfg(feature = "std")]
impl core::fmt::Display for ContractType {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self.0 {
            x if x == Self::kNative.0 => f.write_str("ContractType::kNative"),
            x if x == Self::kMockTest.0 => f.write_str("ContractType::kMockTest"),
            x if x == Self::kRv32.0 => f.write_str("ContractType::kRv32"),
            _ => write!(f, "ContractType({})", self.0),
        }
    }
}

/// A contract that can be deployed to an address and invoked.
///
/// Contracts are the fundamental unit of code execution in Thruput.
/// Once deployed to a `ContractAddress`, they can be invoked by transactions
/// to execute their methods (entrypoints).
///
/// The three contract types serve different purposes:
/// - `kRv32`: User-deployed contracts (most common)
/// - `kNative`: System contracts with privileged access
/// - `kMockTest`: Test contracts for local development
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "xdrs", derive(ReadXDR, WriteXDR, ConstXDRSize))]
#[cfg_attr(feature = "xdrs", xdr(discriminant = "ContractType"))]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[repr(i32)]
#[non_exhaustive]
pub enum Contract {
    /// Identifier for which native contract this is.
    ///
    /// Native contracts are hard-coded in the runtime.
    kNative {
        native_contract_id: HogexecPrecompiledNativeContracts,
    } = ContractType::kNative.0 as i32,
    /// Identifier for the mock contract in the test harness.
    kMockTest { mock_contract_id: i32 } = ContractType::kMockTest.0 as i32,
    kRv32 { rv32_contract: ContractBlob } = ContractType::kRv32.0 as i32,
}

impl Contract {
    #[allow(clippy::match_single_binding)]
    pub fn contract_type(&self) -> ContractType {
        match self {
            Contract::kNative { .. } => ContractType::kNative,
            Contract::kMockTest { .. } => ContractType::kMockTest,
            Contract::kRv32 { .. } => ContractType::kRv32,
        }
    }
}

//------------------------------------------------------------------------------
// Contract Deployment and Address Derivation
//------------------------------------------------------------------------------
/// Hash preimage for deriving deployed contract addresses.
///
/// When a contract deploys another contract, the new contract's address is
/// deterministically computed as:
///
/// ```text
/// ContractAddress = SHA256(ContractDeploymentHashPreimage)
/// ```
///
/// Under XDR encoding, this struct serializes as the concatenation of its
/// fields: `deployer_address || nonce || contract_hash`.
///
/// This is Thruput's analogue of Ethereum's `CREATE2` opcode, allowing
/// deterministic address derivation. The deployer controls the nonce to
/// create addresses at will.
///
/// # Example
///
/// ```text
/// Contract A address:  0x1234...
/// Contract B hash:     0xabcd...   (= SHA256(XDR(Contract B)))
/// Deployment nonce:    0x5678...
/// Result: SHA256(0x1234... || 0x5678... || 0xabcd...) = Contract B address
/// ```
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "xdrs", derive(ReadXDR, WriteXDR, ConstXDRSize))]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(C)]
pub struct ContractDeploymentHashPreimage {
    /// The address of the contract performing the deployment.
    pub deployer_address: ContractAddress,
    /// Arbitrary 32-byte value chosen by the deployer.
    ///
    /// Allows creating multiple instances of the same contract code
    /// at different addresses.
    pub nonce: SHA256Hash,
    /// SHA-256 hash of the XDR-encoded `Contract` being deployed.
    ///
    /// This hashes the entire union, not the bare code blob:
    ///
    /// ```text
    /// contract_hash = SHA256(XDR(Contract))
    /// ```
    ///
    /// The encoding covers the 4-byte `ContractType` discriminant followed by
    /// the selected arm, so identical code deployed under a different contract
    /// type yields a different hash. For `kRv32` the arm is a `ContractBlob`,
    /// which is itself a 4-byte length prefix followed by the code padded to a
    /// 4-byte boundary -- hashing the raw code alone does not reproduce this
    /// value.
    ///
    /// Native and mock contracts are hashed the same way, over a union whose
    /// arm holds a contract identifier instead of a blob. They do not use
    /// separately predefined hash constants.
    pub contract_hash: SHA256Hash,
}

//------------------------------------------------------------------------------
// Contract Interfaces and Entrypoint Derivation
//------------------------------------------------------------------------------
/// 8-byte identifier for a contract method (entrypoint).
///
/// Entrypoint IDs uniquely identify which method to invoke on a contract.
/// A contract may use any 8 bytes; the protocol attaches no meaning to them.
/// By default, the SDK derives them from the interface name, the major
/// version of the interface, and the method name:
///
/// ```text
/// SHA256(name || "::" || major || "::" || method)[0..8]
/// ```
///
/// `major` is the semver compatibility prefix of the interface version: the
/// leading components up to and including the first nonzero one (`"1"` for
/// `"1.4.2"`, `"0.2"` for `"0.2.7"`, `"0.0.3"` for `"0.0.3"`). Versions that
/// share it therefore share entrypoint IDs, and the `"::"` separators keep
/// distinct (name, major, method) triples from concatenating to the same
/// preimage.
///
/// # Example
///
/// For an `"ERC20"` interface at version `"1.0.0"`, `transfer` is
/// `SHA256("ERC20::1::transfer")[0..8]`.
///
/// Interface IDs use the same prefix under a domain tag,
/// `SHA256("thruput-interface::" || name || "::" || major)[0..8]`, so they
/// never coincide with an entrypoint ID.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "xdrs", derive(ReadXDR, WriteXDR, ConstXDRSize))]
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[derive(Default, Copy)]
#[repr(transparent)]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct ContractEntrypointID {
    #[cfg_attr(feature = "serde", serde(with = "xdr_common::serde_hex"))]
    inner: [u8; 8],
}

impl From<[u8; 8]> for ContractEntrypointID {
    fn from(_inner: [u8; 8]) -> Self {
        Self { inner: _inner }
    }
}

impl ContractEntrypointID {
    pub fn into_inner(self) -> [u8; 8] {
        self.inner
    }
    pub const fn new(_inner: [u8; 8]) -> Self {
        Self { inner: _inner }
    }
}

impl Deref for ContractEntrypointID {
    type Target = [u8; 8];
    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl DerefMut for ContractEntrypointID {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.inner
    }
}

impl AsRef<[u8]> for ContractEntrypointID {
    fn as_ref(&self) -> &[u8] {
        self.deref().as_slice()
    }
}

impl<'a> From<&'a [u8; 8]> for &'a ContractEntrypointID {
    fn from(arr: &[u8; 8]) -> Self {
        let ptr = arr as *const [u8; 8] as *const ContractEntrypointID;
        unsafe { &*ptr }
    }
}

#[cfg(feature = "xdrs")]
impl<'r: 'a, 'a> ReadXDR<'r> for &'a ContractEntrypointID {
    fn read_xdr<R: xdrs::Reader<'r>>(r: &mut R) -> xdrs::ReadResult<Self> {
        let arr: &[u8; 8] = xdrs::read_xdr(r)?;
        Ok(Self::from(arr))
    }
}

#[cfg(feature = "schema")]
impl schemars::JsonSchema for ContractEntrypointID {
    fn schema_name() -> ::std::borrow::Cow<'static, str> {
        "ContractEntrypointID".into()
    }
    fn json_schema(_gen: &mut schemars::SchemaGenerator) -> schemars::Schema {
        schemars::json_schema!(
            { "type" : "string", "contentEncoding" : "hex", "contentMediaType" :
            "application/binary", "minLength" : 16, "maxLength" : 16 }
        )
    }
}

//------------------------------------------------------------------------------
// Deployed Contract Metadata
//------------------------------------------------------------------------------
/// Hash and metadata for a contract deployed at an address.
///
/// This allows the system to locate and instantiate the contract code
/// without loading the full contract from storage.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "xdrs", derive(ReadXDR, WriteXDR, ConstXDRSize))]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(C)]
pub struct DeployedContractHash {
    /// SHA-256 hash of the XDR-encoded `Contract` deployed at this address.
    ///
    /// Computed as `SHA256(XDR(Contract))`, identically to the `contract_hash`
    /// field of `ContractDeploymentHashPreimage`.
    pub hash: SHA256Hash,
    /// Size of the contract code in bytes.
    ///
    /// Always 0 for `kNative` and `kMockTest`, which carry no deployable blob.
    ///
    /// Optimization: allows computing and updating storage costs without
    /// loading the full contract from storage.
    pub contract_size: u32,
    /// The type of contract: RV32, native, or mock.
    ///
    /// Optimization: allows the executor to determine which runtime to
    /// instantiate without a database lookup. When the contract module is
    /// already cached, this avoids loading the contract bytecode entirely.
    pub contract_type: ContractType,
}