jam_types/types.rs
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 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
use super::*;
use bounded_collections::ConstU32;
use simple::OpaqueBlsPublic;
/// Plain-old-data struct of the same length and layout to `ValKeyset` struct. This does not
/// bring in any cryptography.
#[derive(Copy, Clone, Encode, Decode, Debug, Eq, PartialEq)]
pub struct OpaqueValKeyset {
/// The opaque Ed25519 public key.
pub ed25519: OpaqueEd25519Public,
/// The opaque Bandersnatch public key.
pub bandersnatch: OpaqueBandersnatchPublic,
/// The opaque BLS public key.
pub bls: OpaqueBlsPublic,
/// The opaque metadata.
pub metadata: OpaqueValidatorMetadata,
}
impl Default for OpaqueValKeyset {
fn default() -> Self {
Self {
ed25519: OpaqueEd25519Public::zero(),
bandersnatch: OpaqueBandersnatchPublic::zero(),
bls: OpaqueBlsPublic::zero(),
metadata: OpaqueValidatorMetadata::zero(),
}
}
}
/// The opaque keys for each validator.
pub type OpaqueValKeysets = FixedVec<OpaqueValKeyset, ConstU32<{ VAL_COUNT as u32 }>>;
/// Reference to a sequence of import segments, which when combined with an index forms a
/// commitment to a specific segment of data.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub enum RootIdentifier {
/// Direct cryptographic commitment to the export-segments tree root.
Direct(SegmentTreeRoot),
/// Indirect reference to the export-segments tree root via a hash of the work-package which
/// resulted in it.
Indirect(WorkPackageHash),
}
impl From<SegmentTreeRoot> for RootIdentifier {
fn from(root: SegmentTreeRoot) -> Self {
Self::Direct(root)
}
}
impl From<WorkPackageHash> for RootIdentifier {
fn from(hash: WorkPackageHash) -> Self {
Self::Indirect(hash)
}
}
impl TryFrom<RootIdentifier> for SegmentTreeRoot {
type Error = WorkPackageHash;
fn try_from(root: RootIdentifier) -> Result<Self, Self::Error> {
match root {
RootIdentifier::Direct(root) => Ok(root),
RootIdentifier::Indirect(hash) => Err(hash),
}
}
}
/// Import segments specification, which identifies a single exported segment.
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct ImportSpec {
/// The identifier of a series of exported segments.
pub root: RootIdentifier,
/// The index into the identified series of exported segments.
pub index: u16,
}
impl Encode for ImportSpec {
fn encode_to<T: scale::Output + ?Sized>(&self, dest: &mut T) {
let off = match &self.root {
RootIdentifier::Direct(root) => {
root.encode_to(dest);
0
},
RootIdentifier::Indirect(hash) => {
hash.encode_to(dest);
1 << 15
},
};
(self.index + off).encode_to(dest);
}
}
impl Decode for ImportSpec {
fn decode<I: scale::Input>(input: &mut I) -> Result<Self, scale::Error> {
let h = Hash::decode(input)?;
let i = u16::decode(input)?;
let root = if i & (1 << 15) == 0 {
SegmentTreeRoot::from(h).into()
} else {
WorkPackageHash::from(h).into()
};
Ok(Self { root, index: i & !(1 << 15) })
}
}
/// Specification of a single piece of extrinsic data.
#[derive(Clone, Encode, Decode, Debug)]
pub struct ExtrinsicSpec {
/// The hash of the extrinsic data.
pub hash: ExtrinsicHash,
/// The length of the extrinsic data.
pub len: u32,
}
/// A definition of work to be done by the Refinement logic of a service and transformed into a
/// [WorkOutput] for its Accumulation logic.
///
/// This is the generic version of the work-item, which is specialized depending on whether and how
/// the extrinsic data is supplied.
#[derive(Clone, Encode, Decode, Debug)]
pub struct GenericWorkItem<Xt> {
/// Service identifier to which this work item relates.
pub service: ServiceId,
/// The service's code hash at the time of reporting. This must be available in-core at the
/// time of the lookup-anchor block.
pub code_hash: CodeHash,
/// Opaque data passed in to the service's Refinement logic to describe its workload.
pub payload: WorkPayload,
/// Gas limit with which to execute this work item's Refine logic.
pub refine_gas_limit: Gas,
/// Gas limit with which to execute this work item's Accumulate logic.
pub accumulate_gas_limit: Gas,
/// Sequence of imported data segments.
pub import_segments: WorkItemImportsVec,
/// Additional data available to the service's Refinement logic while doing its workload.
pub extrinsics: Vec<Xt>,
/// Number of segments exported by this work item.
pub export_count: u16,
}
/// A sequence of import specifications.
pub type WorkItemImportsVec = BoundedVec<ImportSpec, ConstU32<{ MAX_IMPORTS }>>;
/// Various pieces of information helpful to contextualize the Refinement process.
#[derive(Clone, Encode, Decode, Debug, Eq, PartialEq)]
pub struct RefineContext {
/// The most recent header hash of the chain when building. This must be no more than
/// `RECENT_BLOCKS` blocks old when reported.
pub anchor: HeaderHash,
/// Must be state root of block `anchor`. This is checked on-chain when reported.
pub state_root: StateRootHash,
/// Must be Beefy root of block `anchor`. This is checked on-chain when reported.
pub beefy_root: MmrPeakHash,
/// The hash of a header of a block which is final. Availability will not succeed unless a
/// super-majority of validators have attested to this.
/// Preimage `lookup`s will be judged according to this block.
///
/// NOTE: Storage pallet may not cycle more frequently than 48 hours (24 hours above
/// plus 24 hours dispute period).
pub lookup_anchor: HeaderHash,
/// The slot of `lookup_anchor` on the chain. This is checked in availability and the
/// report's package will not be made available without it being correct.
/// This value must be at least `anchor_slot + 14400`.
pub lookup_anchor_slot: Slot,
/// An optional hash of a Work Package, a report of which must be reported prior to this one.
/// This is checked on-chain when reported.
pub prerequisites: VecSet<WorkPackageHash>,
}
// TODO: Refactor away from the generic `Xt` type parameter.
/// A work-package, a collection of work-items together with authorization and contextual
/// information. This is processed _in-core_ with Is-Authorized and Refine logic to produce a
/// work-report.
///
/// This is the generic version of the work-package, which is specialized depending on whether the
/// extrinsic data is actually bundled inside or merely committed to.
#[derive(Clone, Encode, Decode, Debug)]
pub struct GenericWorkPackage<Xt> {
/// Authorization token.
pub authorization: Authorization,
/// Service identifier.
pub auth_code_host: ServiceId,
/// Authorizer.
pub authorizer: Authorizer,
/// Refinement context.
pub context: RefineContext,
/// Sequence of work items.
pub items: GenericWorkItems<Xt>,
}
/// Sequence of [GenericWorkItem]s within a [GenericWorkPackage] and thus limited in length to
/// [MAX_WORK_ITEMS].
pub type GenericWorkItems<Xt> = BoundedVec<GenericWorkItem<Xt>, ConstU32<MAX_WORK_ITEMS>>;
/// Sequence of [WorkItem]s within a [WorkPackage] and thus limited in length to
/// [MAX_WORK_ITEMS].
#[doc(hidden)]
pub type WorkItems = GenericWorkItems<ExtrinsicSpec>;
/// A definition of work to be done by the Refinement logic of a service and transformed into a
/// [WorkOutput] for its Accumulation logic.
///
/// This is a concrete version of the work-item, which only commits to extrinsic data but does not
/// supply it.
pub type WorkItem = GenericWorkItem<ExtrinsicSpec>;
#[doc(hidden)]
pub type FatWorkItem = GenericWorkItem<Vec<u8>>;
#[doc(hidden)]
pub type RefWorkItem = GenericWorkItem<[u8]>;
/// A work-package, a collection of work-items together with authorization and contextual
/// information. This is processed _in-core_ with Is-Authorized and Refine logic to produce a
/// work-report.
///
/// This is a concrete version of the work-package, which only commits to extrinsic data but does
/// not supply it.
pub type WorkPackage = GenericWorkPackage<ExtrinsicSpec>;
#[doc(hidden)]
pub type FatWorkPackage = GenericWorkPackage<Vec<u8>>;
#[doc(hidden)]
pub type RefWorkPackage = GenericWorkPackage<[u8]>;
/// The authorizer tuple which together identifies a means of determining whether a Work Package is
/// acceptable to execute on a core.
#[derive(Clone, Encode, Decode, Debug)]
pub struct Authorizer {
/// Authorization code hash.
pub code_hash: CodeHash,
/// Parameters blob.
pub param: AuthParam,
}
impl Authorizer {
pub fn any() -> Self {
Self { code_hash: CodeHash::zero(), param: Default::default() }
}
}
/// Information on the Work Package, passed into Refine.
#[derive(Clone, Encode, Decode, Debug)]
pub struct PackageInfo {
/// The hash of the Work Package.
pub package_hash: WorkPackageHash,
/// Various pieces of contextual information for the Refinement process.
pub context: RefineContext,
/// The authorizer which was used to authorize the Work Package.
pub authorizer: Authorizer,
/// The output of the Is-Authorized logic which authorized the execution of this work-package.
pub auth_output: AuthOutput,
}
/// Potential errors encountered during the refinement of a [`WorkItem`].
///
/// Although additional errors may be generated internally by the PVM engine,
/// these are the specific errors designated by the GP for the [`WorkResult`]
/// and that are eligible to be forwarded to the accumulate process as part
/// of the [`AccumulateItem`].
#[derive(Clone, Encode, Decode, Debug, Eq, PartialEq)]
#[doc(hidden)]
pub enum WorkError {
/// Gas exhausted (∞).
OutOfGas = 1,
/// Unexpected termination (☇).
Panic = 2,
/// Invalid amount of segments exported.
BadExports = 3,
/// Bad code for the service (`BAD`).
///
/// This may occur due to an unknown service identifier or unavailable code preimage.
BadCode = 4,
/// Out of bounds code size (`BIG`).
CodeOversize = 5,
}
/// The result and surrounding context of a single Refinement operation passed as part of a Work
/// Report.
#[derive(Clone, Encode, Decode, Debug, Eq, PartialEq)]
#[doc(hidden)]
pub struct WorkResult {
/// The service whose Refinement gave this result.
pub service: ServiceId,
/// The service's code hash at the time of reporting. This must be available in-core at the
/// time of the lookup-anchor block.
pub code_hash: CodeHash,
/// The hash of the payload data passed into Refinement which gave this result.
pub payload_hash: PayloadHash,
/// The amount of gas to be used for the accumulation of this result.
pub accumulate_gas: Gas,
/// The result of the Refinement operation itself.
#[codec(encoded_as = "CompactRefineResult")]
pub result: Result<WorkOutput, WorkError>,
}
/// The result and surrounding context of a single Refinement operation passed in to the
/// Accumulation logic.
#[derive(Debug, Encode, Decode)]
pub struct AccumulateItem {
/// The hash of the work-package in which the work-item which gave this result was placed.
pub package: WorkPackageHash,
/// The output of the Is-Authorized logic which authorized the execution of the work-package
/// which generated this result.
pub auth_output: AuthOutput,
/// The hash of the payload data passed into Refinement which gave this result.
pub payload: PayloadHash,
/// The result of the Refinement operation itself.
#[codec(encoded_as = "CompactRefineResult")]
pub result: Result<WorkOutput, WorkError>,
}
/// Parameters for the invocation of Accumulate.
#[derive(Debug, Encode, Decode)]
#[doc(hidden)]
pub struct AccumulateParams {
/// The current time slot.
pub slot: Slot,
/// The index of the service being accumulated.
pub id: ServiceId,
/// A sequence of work-results to accumulate.
pub results: Vec<AccumulateItem>,
}
/// A single deferred transfer of balance and/or data, passed in to the invocation of On Transfer.
#[derive(Debug, Clone, Encode, Decode)]
pub struct TransferRecord {
/// The index of the service from which the transfer was made.
pub source: ServiceId,
/// The index of the service which is the target of the transfer.
pub destination: ServiceId,
/// The balance passed from the `source` service to the `destination`.
pub amount: Balance,
/// The information passed from the `source` service to the `destination`.
pub memo: Memo,
/// The gas limit with which the `destination` On Transfer logic may execute in order to
/// process this transfer.
pub gas_limit: Gas,
}
impl Default for TransferRecord {
fn default() -> Self {
Self {
source: Default::default(),
destination: Default::default(),
amount: Default::default(),
memo: Memo::zero(),
gas_limit: Default::default(),
}
}
}
/// Parameters for the invocation of On Transfer.
#[derive(Debug, Encode, Decode)]
#[doc(hidden)]
pub struct OnTransferParams {
/// The current time slot.
pub slot: Slot,
/// The index of the service to which the transfers are being made.
pub id: ServiceId,
/// The sequence of transfers to be processed.
pub transfers: Vec<TransferRecord>,
}
/// Parameters for the invocation of Refine.
#[derive(Debug, Encode, Decode)]
#[doc(hidden)]
pub struct RefineParams {
/// The index of the service being refined.
pub id: ServiceId,
/// The payload data to process.
pub payload: WorkPayload,
/// Information on the package which caused this invocation.
pub package_info: PackageInfo,
/// The extrinsic data concerning this payload.
pub extrinsics: Vec<Vec<u8>>,
}
// TODO: @gav Consider moving to jam-node.
/// Parameters for the invocation of Refine, reference variant.
#[derive(Debug, Encode)]
#[doc(hidden)]
pub struct RefineParamsRef<'a, T: 'a + core::fmt::Debug + Encode> {
/// The index of the service being refined.
pub id: ServiceId,
/// The payload data to process.
pub payload: &'a WorkPayload,
/// Information on the package which caused this invocation.
pub package_info: &'a PackageInfo,
/// The extrinsic data concerning this payload.
pub extrinsics: &'a [T],
}
// TODO: @gav Consider moving to jam-node.
/// Parameters for the invocation of On Transfer, reference variant.
#[derive(Debug, Encode)]
#[doc(hidden)]
pub struct OnTransferParamsRef<'a> {
/// The current time slot.
pub slot: Slot,
/// The index of the service to which the transfers are being made.
pub id: ServiceId,
/// The sequence of transfers to be processed.
pub transfers: &'a [TransferRecord],
}
/// Information concerning a particular service's state.
///
/// This is used in the `service_info` host-call.
#[derive(Debug, Clone, Encode, Decode, MaxEncodedLen)]
pub struct ServiceInfo {
/// The hash of the code of the service.
pub code_hash: CodeHash,
/// The existing balance of the service.
pub balance: Balance,
/// The minimum balance which the service must satisfy.
pub threshold: Balance,
/// The minimum amount of gas which must be provided to this service's `accumulate` for each
/// work item it must process.
pub min_item_gas: Gas,
/// The minimum amount of gas which must be provided to this service's `on_transfer` for each
/// memo (i.e. transfer receipt) it must process.
pub min_memo_gas: Gas,
/// The total number of bytes used for data electively held for this service on-chain.
pub bytes: u64,
/// The total number of items of data electively held for this service on-chain.
pub items: u32,
}
impl scale::ConstEncodedLen for ServiceInfo {}
/// Refine result used for compact encoding of work result as prescribed by GP.
struct CompactRefineResult(Result<WorkOutput, WorkError>);
struct CompactRefineResultRef<'a>(&'a Result<WorkOutput, WorkError>);
impl From<CompactRefineResult> for Result<WorkOutput, WorkError> {
fn from(value: CompactRefineResult) -> Self {
value.0
}
}
impl<'a> From<&'a Result<WorkOutput, WorkError>> for CompactRefineResultRef<'a> {
fn from(value: &'a Result<WorkOutput, WorkError>) -> Self {
CompactRefineResultRef(value)
}
}
impl<'a> scale::EncodeAsRef<'a, Result<WorkOutput, WorkError>> for CompactRefineResult {
type RefType = CompactRefineResultRef<'a>;
}
impl Encode for CompactRefineResult {
fn encode_to<T: scale::Output + ?Sized>(&self, dest: &mut T) {
CompactRefineResultRef(&self.0).encode_to(dest)
}
}
impl Encode for CompactRefineResultRef<'_> {
fn encode_to<T: scale::Output + ?Sized>(&self, dest: &mut T) {
match &self.0 {
Ok(o) => {
dest.push_byte(0);
o.encode_to(dest)
},
Err(e) => e.encode_to(dest),
}
}
}
impl Decode for CompactRefineResult {
fn decode<I: scale::Input>(input: &mut I) -> Result<Self, scale::Error> {
match input.read_byte()? {
0 => Ok(Self(Ok(WorkOutput::decode(input)?))),
e => Ok(Self(Err(WorkError::decode(&mut &[e][..])?))),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn compact_refine_result_codec() {
let enc_dec = |exp_res, exp_buf: &[u8]| {
let buf = CompactRefineResultRef(&exp_res).encode();
assert_eq!(buf, exp_buf);
let res = CompactRefineResult::decode(&mut &buf[..]).unwrap();
assert_eq!(res.0, exp_res);
};
enc_dec(Ok(vec![1, 2, 3].into()), &[0, 3, 1, 2, 3]);
enc_dec(Err(WorkError::OutOfGas), &[1]);
enc_dec(Err(WorkError::Panic), &[2]);
enc_dec(Err(WorkError::BadExports), &[3]);
enc_dec(Err(WorkError::BadCode), &[4]);
enc_dec(Err(WorkError::CodeOversize), &[5]);
}
}