diff --git a/.sqlx/query-9e9da3f0fa8255b95befdfd158c3eb98012ca135a793052adb114c6a8b038608.json b/.sqlx/query-0d5930bb5e4efc7be9b5603ea62fc35d5150cf6a1634580ab9aea9ccf69a9896.json similarity index 54% rename from .sqlx/query-9e9da3f0fa8255b95befdfd158c3eb98012ca135a793052adb114c6a8b038608.json rename to .sqlx/query-0d5930bb5e4efc7be9b5603ea62fc35d5150cf6a1634580ab9aea9ccf69a9896.json index 61d586d..7b46cfc 100644 --- a/.sqlx/query-9e9da3f0fa8255b95befdfd158c3eb98012ca135a793052adb114c6a8b038608.json +++ b/.sqlx/query-0d5930bb5e4efc7be9b5603ea62fc35d5150cf6a1634580ab9aea9ccf69a9896.json @@ -1,60 +1,62 @@ { "db_name": "PostgreSQL", - "query": "\n select height, event_index, pallet, variant, phase, extrinsic_index,\n fields as \"fields!\", at, accounts as \"accounts!\"\n from chain_event\n where chain = $1 and accounts @> array[$2]\n and (height, event_index) < ($3, $4)\n order by height desc, event_index desc\n limit $5\n ", + "query": "\n select extrinsic_index, pallet, call, signer, signature, signature_bytes,\n args as \"args!\", extra, success, at\n from chain_extrinsic\n where chain = $1 and height = $2\n order by extrinsic_index asc\n ", "describe": { "columns": [ { "ordinal": 0, - "name": "height", - "type_info": "Int8" - }, - { - "ordinal": 1, - "name": "event_index", - "type_info": "Int4" - }, - { - "ordinal": 2, - "name": "pallet", - "type_info": "Text" - }, - { - "ordinal": 3, - "name": "variant", - "type_info": "Text" - }, - { - "ordinal": 4, - "name": "phase", - "type_info": "Text" - }, - { - "ordinal": 5, "name": "extrinsic_index", "type_info": "Int4" }, + { + "ordinal": 1, + "name": "pallet", + "type_info": "Text" + }, + { + "ordinal": 2, + "name": "call", + "type_info": "Text" + }, + { + "ordinal": 3, + "name": "signer", + "type_info": "Text" + }, + { + "ordinal": 4, + "name": "signature", + "type_info": "Text" + }, + { + "ordinal": 5, + "name": "signature_bytes", + "type_info": "Int4" + }, { "ordinal": 6, - "name": "fields!", + "name": "args!", "type_info": "Jsonb" }, { "ordinal": 7, - "name": "at", - "type_info": "Timestamptz" + "name": "extra", + "type_info": "Jsonb" }, { "ordinal": 8, - "name": "accounts!", - "type_info": "TextArray" + "name": "success", + "type_info": "Bool" + }, + { + "ordinal": 9, + "name": "at", + "type_info": "Timestamptz" } ], "parameters": { "Left": [ "Text", - "Text", - "Int8", - "Int4", "Int8" ] }, @@ -62,13 +64,14 @@ false, false, false, + true, + true, false, false, true, - false, true, - false + true ] }, - "hash": "9e9da3f0fa8255b95befdfd158c3eb98012ca135a793052adb114c6a8b038608" + "hash": "0d5930bb5e4efc7be9b5603ea62fc35d5150cf6a1634580ab9aea9ccf69a9896" } diff --git a/.sqlx/query-75269c74d30e7a8386a84206a9d4f3b392048e47d076a47d9fdbe9dc4a8f26a4.json b/.sqlx/query-75269c74d30e7a8386a84206a9d4f3b392048e47d076a47d9fdbe9dc4a8f26a4.json new file mode 100644 index 0000000..6661b05 --- /dev/null +++ b/.sqlx/query-75269c74d30e7a8386a84206a9d4f3b392048e47d076a47d9fdbe9dc4a8f26a4.json @@ -0,0 +1,87 @@ +{ + "db_name": "PostgreSQL", + "query": "\n with merged as (\n select 1 as source, height, extrinsic_index as idx, pallet,\n call as name, args as payload, at, signer, success,\n null::text as phase, accounts\n from chain_extrinsic\n where chain = $1 and accounts @> array[$2]\n union all\n select 0 as source, height, event_index as idx, pallet,\n variant as name, fields as payload, at,\n null::text as signer, null::boolean as success, phase,\n accounts\n from chain_event\n where chain = $1 and accounts @> array[$2]\n )\n select source as \"source!\", height as \"height!\", idx as \"idx!\",\n pallet as \"pallet!\", name as \"name!\", payload as \"payload!\",\n at, signer, success, phase, accounts as \"accounts!\"\n from merged\n where (height, source, idx) < ($3, $4, $5)\n order by height desc, source desc, idx desc\n limit $6\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "source!", + "type_info": "Int4" + }, + { + "ordinal": 1, + "name": "height!", + "type_info": "Int8" + }, + { + "ordinal": 2, + "name": "idx!", + "type_info": "Int4" + }, + { + "ordinal": 3, + "name": "pallet!", + "type_info": "Text" + }, + { + "ordinal": 4, + "name": "name!", + "type_info": "Text" + }, + { + "ordinal": 5, + "name": "payload!", + "type_info": "Jsonb" + }, + { + "ordinal": 6, + "name": "at", + "type_info": "Timestamptz" + }, + { + "ordinal": 7, + "name": "signer", + "type_info": "Text" + }, + { + "ordinal": 8, + "name": "success", + "type_info": "Bool" + }, + { + "ordinal": 9, + "name": "phase", + "type_info": "Text" + }, + { + "ordinal": 10, + "name": "accounts!", + "type_info": "TextArray" + } + ], + "parameters": { + "Left": [ + "Text", + "Text", + "Int8", + "Int4", + "Int4", + "Int8" + ] + }, + "nullable": [ + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null + ] + }, + "hash": "75269c74d30e7a8386a84206a9d4f3b392048e47d076a47d9fdbe9dc4a8f26a4" +} diff --git a/.sqlx/query-c0bc24a0ac524e0ef577158d8d3159c6aadddc4cfb3b076fc417faf51d642c5d.json b/.sqlx/query-c0bc24a0ac524e0ef577158d8d3159c6aadddc4cfb3b076fc417faf51d642c5d.json new file mode 100644 index 0000000..e3038c6 --- /dev/null +++ b/.sqlx/query-c0bc24a0ac524e0ef577158d8d3159c6aadddc4cfb3b076fc417faf51d642c5d.json @@ -0,0 +1,26 @@ +{ + "db_name": "PostgreSQL", + "query": "\n insert into chain_extrinsic\n (chain, height, extrinsic_index, pallet, call, signer, signature,\n signature_bytes, args, extra, success, accounts, at)\n select chain, height, extrinsic_index, pallet, call, signer, signature,\n signature_bytes, args, extra, success,\n array(select jsonb_array_elements_text(accounts)), at\n from unnest(\n $1::text[], $2::bigint[], $3::int[], $4::text[], $5::text[], $6::text[],\n $7::text[], $8::int[], $9::jsonb[], $10::jsonb[], $11::bool[], $12::jsonb[],\n $13::timestamptz[]\n ) as t(chain, height, extrinsic_index, pallet, call, signer, signature,\n signature_bytes, args, extra, success, accounts, at)\n on conflict (chain, height, extrinsic_index) do update set\n pallet = excluded.pallet,\n call = excluded.call,\n signer = excluded.signer,\n signature = excluded.signature,\n signature_bytes = excluded.signature_bytes,\n args = excluded.args,\n extra = excluded.extra,\n success = coalesce(excluded.success, chain_extrinsic.success),\n accounts = excluded.accounts,\n at = coalesce(excluded.at, chain_extrinsic.at)\n ", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "TextArray", + "Int8Array", + "Int4Array", + "TextArray", + "TextArray", + "TextArray", + "TextArray", + "Int4Array", + "JsonbArray", + "JsonbArray", + "BoolArray", + "JsonbArray", + "TimestamptzArray" + ] + }, + "nullable": [] + }, + "hash": "c0bc24a0ac524e0ef577158d8d3159c6aadddc4cfb3b076fc417faf51d642c5d" +} diff --git a/CLAUDE.md b/CLAUDE.md index 94d9af6..0e39927 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -116,6 +116,19 @@ it is what makes trying the tip's runtime speculatively safe, and what triggers check to tolerate trailing bytes would turn a loud failure into silently wrong rewards. +**An extrinsic's first byte is not its version.** The top two bits are a type +tag — `0b10` signed, `0b00` bare, `0b01` general — and only the low six are the +version. Mainnet emits `0x84` (signed, v4) and `0x05` (bare, v**5**) in the same +block while the metadata declares extrinsic version 4. A decoder that reads the +byte as a version and checks it against the metadata rejects every timestamp +inherent on the chain. + +**Never store a signature.** Dilithium is **5.3 KiB** per transaction — two +orders of magnitude larger than the call it authorises. `decode_extrinsic` +decodes it because that is the only way to know where the call begins, then +keeps the scheme's *name* and the byte count and discards the bytes. At a block +a second, storing them would be gigabytes a month that nothing renders. + **Backfill progress is a cursor, not `max(height) from chain_event`.** A block with no indexed event and a block never looked at give the same answer, and the first is the common case — `INDEXED_EVENTS` is deliberately narrow. Inferring diff --git a/Cargo.lock b/Cargo.lock index 3ef2d5b..767a500 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -250,6 +250,7 @@ dependencies = [ "clap", "figment", "futures-util", + "hex", "primitive-types", "serde", "serde_json", diff --git a/crates/blackbeard-api/Cargo.toml b/crates/blackbeard-api/Cargo.toml index 5f1f17b..299ff34 100644 --- a/crates/blackbeard-api/Cargo.toml +++ b/crates/blackbeard-api/Cargo.toml @@ -23,6 +23,7 @@ chrono.workspace = true clap.workspace = true figment.workspace = true futures-util.workspace = true +hex.workspace = true primitive-types.workspace = true serde.workspace = true sqlx.workspace = true diff --git a/crates/blackbeard-api/src/ingest.rs b/crates/blackbeard-api/src/ingest.rs index ab45e2d..4b454b6 100644 --- a/crates/blackbeard-api/src/ingest.rs +++ b/crates/blackbeard-api/src/ingest.rs @@ -729,18 +729,18 @@ async fn index_events( // into plausible nonsense — which is what makes trying it speculatively // safe, and what the fallback below is for. let decoded = match chain.read().current_runtime() { - Some(runtime) => runtime.decode_events(&blob).ok(), + Some(runtime) => runtime.decode_events(&blob).ok().map(|d| (d, runtime)), None => None, }; - let decoded = match decoded { - Some(d) => d, + let (decoded, runtime) = match decoded { + Some((d, r)) => (d, r), None => { let Some(runtime) = runtime_at(chain, store, hash).await else { return Indexed::Unreadable; }; match runtime.decode_events(&blob) { - Ok(d) => d, + Ok(d) => (d, runtime), Err(e) => { // The runtime the chain itself says produced this block // cannot read it. That is this decoder's limitation, not a @@ -752,18 +752,42 @@ async fn index_events( } }; - // The chain's own clock rather than the observer's: an account's rewards - // run back to genesis, and most of them predate this process. One more - // call, and `None` if the node declines — a reward with no date is still a - // reward. - let at = chain - .rpc - .block_timestamp_ms(hash) - .await - .ok() - .flatten() + // The body, for its timestamp and its extrinsics both. One call rather + // than two: the chain's own clock lives in the first extrinsic, and asking + // for it separately would fetch the same block twice. + let body = chain.rpc.body(hash).await.ok().flatten(); + let at = body + .as_ref() + .and_then(|b| b.timestamp_ms) .and_then(from_millis); + // Which extrinsics the chain reported as failing, from events already in + // hand. Storing `System::ExtrinsicSuccess` as rows would be two per block + // forever for one boolean each; reading them here costs nothing, because + // the whole event list is already decoded. + let outcomes: std::collections::HashMap = decoded + .iter() + .filter(|e| e.pallet == "System") + .filter_map(|e| match e.variant.as_str() { + "ExtrinsicSuccess" => Some((e.extrinsic_index?, true)), + "ExtrinsicFailed" => Some((e.extrinsic_index?, false)), + _ => None, + }) + .collect(); + + if let Some(body) = body { + index_extrinsics( + chain, + store, + height, + &body.extrinsics, + &outcomes, + at, + &runtime, + ) + .await; + } + let keep: Vec = decoded .into_iter() .filter(|e| is_indexed(&e.pallet, &e.variant)) @@ -793,6 +817,65 @@ async fn index_events( } } +/// Store a block's extrinsics, decoded against the runtime that produced it. +/// +/// Best effort, like the events beside it: an extrinsic that will not decode +/// costs the site that row and nothing else. It must never stop ingest, and it +/// must never be stored half-read — `decode_extrinsic` refuses a partial read +/// for the same reason `decode_events` does. +/// +/// Every extrinsic is kept, inherents included. There is no `INDEXED_EVENTS` +/// equivalent here because there is nothing to filter out: a block carries two +/// or three extrinsics, not the fifty events an event list holds, and the +/// timestamp inherent is the block's own clock rather than noise. +async fn index_extrinsics( + chain: &Arc, + store: &Store, + height: u64, + raw: &[String], + outcomes: &std::collections::HashMap, + at: Option>, + runtime: &Arc, +) { + let mut keep = Vec::with_capacity(raw.len()); + for (index, hex_str) in raw.iter().enumerate() { + let Ok(bytes) = hex::decode(hex_str.trim_start_matches("0x")) else { + continue; + }; + let index = index as u32; + match runtime.decode_extrinsic(index, &bytes) { + Ok(x) => keep.push(blackbeard_data::store::ExtrinsicRecord { + chain: chain.id(), + height, + extrinsic_index: index, + pallet: x.pallet, + call: x.call, + signer: x.signer, + signature: x.signature, + signature_bytes: x.signature_bytes, + args: x.args, + extra: x.extra, + success: outcomes.get(&index).copied(), + accounts: x.accounts, + at, + }), + Err(e) => { + tracing::debug!( + chain = %chain.id(), height, index, error = %e, + "extrinsic did not decode" + ); + } + } + } + + if keep.is_empty() { + return; + } + if let Err(e) = store.record_extrinsics(&keep).await { + tracing::warn!(chain = %chain.id(), height, error = %e, "extrinsics not persisted"); + } +} + /// Read every block's events from the tip back to genesis, and keep up. /// /// Live ingest indexes each block as it arrives, which is enough for a feed and diff --git a/crates/blackbeard-api/src/routes.rs b/crates/blackbeard-api/src/routes.rs index 67ddffb..5eb5dbf 100644 --- a/crates/blackbeard-api/src/routes.rs +++ b/crates/blackbeard-api/src/routes.rs @@ -16,9 +16,9 @@ use axum::response::{IntoResponse, Response}; use axum::routing::get; use axum::{Json, Router}; use blackbeard_entities::{ - AccountDetail, AccountEvent, AccountRow, ApiError, BigUintDec, BlockDetail, ChainInfo, - ChainSeries, ChainSummary, LeaderboardRow, MinerDetail, MinerId, MinerSeriesPoint, RecentBlock, - RewardSummary, RuntimeConstant, RuntimeDetail, RuntimeField, RuntimePallet, + AccountDetail, AccountEvent, AccountRow, ActivitySource, ApiError, BigUintDec, BlockDetail, + ChainInfo, ChainSeries, ChainSummary, LeaderboardRow, MinerDetail, MinerId, MinerSeriesPoint, + RecentBlock, RewardSummary, RuntimeConstant, RuntimeDetail, RuntimeField, RuntimePallet, RuntimeSignedExtension, RuntimeStorage, RuntimeSummary, RuntimeVariant, Window, }; use serde::{Deserialize, Serialize}; @@ -368,7 +368,7 @@ async fn from_hash( let body = runtime.rpc.body(hash).await.ok().flatten(); let miner = blackbeard_core::digest::author_preimage(&header.digest.logs); - let authored_at = body.and_then(|b| b.timestamp_ms).and_then(millis); + let authored_at = body.as_ref().and_then(|b| b.timestamp_ms).and_then(millis); // The parent's timestamp, for how long this block took to find. Asked of the // node by parent hash rather than read at height-1, so it is this block's @@ -414,7 +414,8 @@ async fn from_hash( at_tip: ours.as_ref().map(|r| r.at_tip), miner, seconds_since_parent, - extrinsics: body.map(|b| b.extrinsics), + extrinsics: body.map(|b| b.extrinsics.len() as u32), + body: block_body(state, &id, height).await, canonical, canonical_hash, also_seen: other_hashes(state, &id, height, hash).await, @@ -422,6 +423,63 @@ async fn from_hash( }) } +/// A block's extrinsics out of the index. +/// +/// The count on a block page comes from the body and goes when the node forgets +/// the block; these come from this observer's own record and do not. Empty for +/// a block the index has not reached, which the page distinguishes from a block +/// with nothing in it. +async fn block_body( + state: &AppState, + chain: &blackbeard_entities::ChainId, + height: u64, +) -> Vec { + let Ok(rows) = state.store.extrinsics_at(chain, height).await else { + return Vec::new(); + }; + rows.into_iter() + .map(|x| blackbeard_entities::BlockExtrinsic { + index: x.extrinsic_index, + pallet: x.pallet, + call: x.call, + signer_address: x + .signer + .as_deref() + .and_then(blackbeard_core::wormhole::ss58_of), + addresses: collect_addresses(&x.args), + signer: x.signer, + signature: x.signature, + signature_bytes: x.signature_bytes, + args: x.args, + success: x.success, + }) + .collect() +} + +/// Every account id anywhere in a decoded payload, as `0x hex → SS58`. +/// +/// Walks the whole tree rather than the top level: a `Utility::batch_all` +/// carries entire calls in its arguments, so a transfer's recipient can be +/// three levels down. The decoder's own account list is not used here because +/// it includes the signer and this is about what the call names. +fn collect_addresses(value: &serde_json::Value) -> std::collections::BTreeMap { + let mut out = std::collections::BTreeMap::new(); + let mut stack = vec![value]; + while let Some(v) = stack.pop() { + match v { + serde_json::Value::String(s) => { + if let Some(address) = blackbeard_core::wormhole::ss58_of(s) { + out.insert(s.clone(), address); + } + } + serde_json::Value::Array(items) => stack.extend(items.iter()), + serde_json::Value::Object(map) => stack.extend(map.values()), + _ => {} + } + } + out +} + /// Describe a block from what the observer recorded, the node having failed to /// answer for it. async fn from_record( @@ -433,6 +491,7 @@ async fn from_record( ) -> BlockDetail { let id = runtime.id(); let attribution = runtime.attribute(&recorded.miner); + let body = block_body(state, &id, recorded.height).await; BlockDetail { chain: id.clone(), height: recorded.height, @@ -442,6 +501,7 @@ async fn from_record( parent_hash: None, seconds_since_parent: None, extrinsics: None, + body, display: Some(attribution.display), attribution: Some(attribution.source), confidence: Some(attribution.confidence), @@ -828,10 +888,15 @@ fn parse_spec(raw: &str) -> Result { /// arrive as a single response. const ACTIVITY_PAGE: i64 = 100; -/// Paging cursor: the `(height, event_index)` of the last row already seen. +/// Paging cursor: the `(height, source, index)` of the last row already seen. +/// +/// Three parts because the history merges two tables and a block can hold rows +/// from both. `source` is 1 for an extrinsic and 0 for an event, which is what +/// puts a request above the results it caused. #[derive(Debug, Deserialize)] struct ActivityQuery { before_height: Option, + before_source: Option, before_index: Option, } @@ -849,10 +914,10 @@ async fn account( let account = parse_address(&address)?; let id = runtime.id(); - // A cursor is only a cursor with both halves; half of one would silently - // page from event zero of that height and repeat a row. - let before = match (query.before_height, query.before_index) { - (Some(h), Some(i)) => Some((h, i)), + // A cursor is only a cursor with all three parts; a partial one would + // silently page from the top of that height and repeat rows. + let before = match (query.before_height, query.before_source, query.before_index) { + (Some(h), Some(s), Some(i)) => Some((h, s, i)), _ => None, }; @@ -863,7 +928,7 @@ async fn account( .map_err(database_unavailable)?; let activity = state .store - .account_events(&id, &account, before, ACTIVITY_PAGE) + .account_activity(&id, &account, before, ACTIVITY_PAGE) .await .map_err(database_unavailable)?; let miner = state @@ -909,19 +974,28 @@ async fn account( }, activity: activity .into_iter() - .map(|e| AccountEvent { - height: e.height, - event_index: e.event_index, - pallet: e.pallet, - variant: e.variant, - fields: e.fields, - at: e.at, - addresses: e + .map(|row| AccountEvent { + // 1 and 0 are the sort ranks the store orders on; naming them + // here keeps that arithmetic out of the wire format. + source: if row.source == 1 { + ActivitySource::Extrinsic + } else { + ActivitySource::Event + }, + height: row.height, + index: row.index, + pallet: row.pallet, + name: row.name, + signer: row.signer, + success: row.success, + fields: row.payload, + at: row.at, + addresses: row .accounts .into_iter() - .filter_map(|hex| { - let address = blackbeard_core::wormhole::ss58_of(&hex)?; - Some((hex, address)) + .filter_map(|id| { + let address = blackbeard_core::wormhole::ss58_of(&id)?; + Some((id, address)) }) .collect(), }) diff --git a/crates/blackbeard-core/src/runtime.rs b/crates/blackbeard-core/src/runtime.rs index 61bf0d1..688181c 100644 --- a/crates/blackbeard-core/src/runtime.rs +++ b/crates/blackbeard-core/src/runtime.rs @@ -83,6 +83,46 @@ pub struct DecodedEvent { pub accounts: Vec, } +/// One decoded extrinsic, named as the runtime names it. +#[derive(Debug, Clone, PartialEq)] +pub struct DecodedExtrinsic { + /// Position in the block's body, which with the height is its identity and + /// what the `ApplyExtrinsic` phase of an event refers to. + pub index: u32, + /// Extrinsic format version from the preamble byte. + pub version: u8, + /// Whether it carries a signature. `false` is an inherent — the timestamp, + /// mostly — which the block author inserted rather than anyone submitting. + pub signed: bool, + /// The signing account as `0x` hex, when the address is a plain account id. + /// `None` for an inherent, and for an address form that is not an id. + pub signer: Option, + /// The signature scheme's variant name, e.g. `Dilithium65`. + /// + /// The name only. A Dilithium signature is **5.3 KiB** on this chain — at a + /// block a second, storing them is gigabytes a month of bytes nothing + /// renders. It is decoded because that is the only way to know where the + /// call begins, and then discarded. + pub signature: Option, + /// How many bytes that signature took, which is worth showing precisely + /// because it is the single most surprising number about a Quantus + /// transaction. + pub signature_bytes: u32, + /// Dispatching pallet, e.g. `Balances`. + pub pallet: String, + /// The call, e.g. `transfer_allow_death`. + pub call: String, + /// Call arguments, normalised the same way event fields are. Nested: a + /// `Utility::batch_all` carries whole calls in here. + pub args: serde_json::Value, + /// The signed extensions as submitted — mortality, nonce, tip. `Null` for + /// an inherent, which signs nothing and so carries none. + pub extra: serde_json::Value, + /// Every account this extrinsic mentions anywhere, including inside nested + /// calls, as `0x` hex. The signer is included. + pub accounts: Vec, +} + /// What a runtime says about itself, read out of its own type registry. #[derive(Debug, Clone, PartialEq)] pub struct RuntimeDescription { @@ -179,6 +219,15 @@ pub struct SignedExtensionDescription { pub additional: String, } +/// The four type parameters of the extrinsic envelope. +#[derive(Debug, Clone, Copy)] +struct ExtrinsicTypes { + address: u32, + signature: u32, + extra: u32, + call: u32, +} + /// A runtime's description of itself, ready to decode with. pub struct Runtime { metadata: RuntimeMetadataV14, @@ -186,6 +235,11 @@ pub struct Runtime { /// Type ids whose registry path ends in a name worth rendering specially. /// Resolved once here rather than looked up per value. account_tys: BTreeMap, + /// The four type parameters of `UncheckedExtrinsic`, resolved once: + /// address, signature, signed extensions, call. Absent only if the runtime + /// does not describe its extrinsic in the usual shape, in which case + /// extrinsics do not decode and events still do. + extrinsic_tys: Option, /// Type ids of the big-integer newtypes, with how many `u64` limbs each /// carries. Same trick as `account_tys` and for the same reason: the /// registry describes `U512` as eight numbers, which is true and useless. @@ -262,9 +316,34 @@ impl Runtime { }) .collect(); + // The envelope's four parameters, by the names `UncheckedExtrinsic` + // gives them. Read from the registry rather than assumed, which is the + // whole point: `Signature` here is + // `qp_dilithium_crypto::types::DilithiumSignatureScheme`, and no + // decoder written against vanilla Substrate would guess that. + let extrinsic_tys = metadata + .types + .resolve(metadata.extrinsic.ty.id) + .and_then(|e| { + let param = |name: &str| { + e.type_params + .iter() + .find(|p| p.name == name) + .and_then(|p| p.ty) + .map(|t| t.id) + }; + Some(ExtrinsicTypes { + address: param("Address")?, + signature: param("Signature")?, + extra: param("Extra")?, + call: param("Call")?, + }) + }); + Ok(Self { metadata, events_ty, + extrinsic_tys, account_tys, bigint_tys, }) @@ -278,6 +357,176 @@ impl Runtime { .map(|p| (p.index, p.name.as_str())) } + /// Decode one extrinsic, exactly as its runtime describes it. + /// + /// ## The envelope + /// + /// A SCALE-encoded extrinsic is a length prefix, one preamble byte, and + /// then — if it is signed — the address, the signature and the signed + /// extensions, before the call itself. Every one of those four is a type in + /// the registry rather than something this decoder knows: on Quantus the + /// signature is `DilithiumSignatureScheme` and the extensions include + /// `ReversibleTransactionExtension` and `WormholeProofRecorderExtension`, + /// none of which exists in Substrate. Reading them out of the metadata is + /// what makes this work at all, and what makes it keep working across the + /// upgrade that changes them. + /// + /// ## The preamble byte is not the version + /// + /// The **top two bits are a type tag** and the low six are the version: + /// `0b10` signed, `0b00` bare, `0b01` general. Mainnet emits `0x84` — + /// signed, v4 — and `0x05` — bare, v**5** — in the same block, while the + /// metadata declares version 4. A decoder that reads the byte as a version + /// and checks it against the metadata rejects every timestamp inherent on + /// the chain. + /// + /// Refuses a partial read, for the same reason `decode_events` does. + pub fn decode_extrinsic( + &self, + index: u32, + blob: &[u8], + ) -> Result { + let tys = self + .extrinsic_tys + .ok_or_else(|| RuntimeError::Decode("runtime describes no extrinsic type".into()))?; + + let mut cursor = blob; + // The body's own length, which the node hands over as part of the blob. + let declared = + as parity_scale_codec::Decode>::decode(&mut cursor) + .map_err(|e| RuntimeError::Decode(format!("no length prefix: {e}")))? + .0 as usize; + if cursor.len() != declared { + return Err(RuntimeError::Decode(format!( + "declared {declared} bytes, {} present", + cursor.len() + ))); + } + + let preamble = *cursor + .first() + .ok_or_else(|| RuntimeError::Decode("empty extrinsic".into()))?; + cursor = &cursor[1..]; + let signed = preamble & 0b1100_0000 == 0b1000_0000; + let version = preamble & 0b0011_1111; + + let mut accounts = BTreeSet::new(); + let (signer, signature, signature_bytes, extra) = if signed { + let address = self.decode_at(tys.address, &mut cursor, "address")?; + let signer = self.sole_account(&address, &mut accounts); + + let before = cursor.len(); + let signature = self.decode_at(tys.signature, &mut cursor, "signature")?; + // The name, not the bytes: 5.3 KiB of Dilithium per transaction is + // not something to keep a copy of, and nothing renders it. + let kind = match &signature.value { + scale_value::ValueDef::Variant(v) => Some(v.name.clone()), + _ => None, + }; + let consumed = (before - cursor.len()) as u32; + + let extra = self.decode_at(tys.extra, &mut cursor, "signed extensions")?; + ( + signer, + kind, + consumed, + self.normalise(&extra, &mut accounts), + ) + } else { + (None, None, 0, serde_json::Value::Null) + }; + + let call = self.decode_at(tys.call, &mut cursor, "call")?; + if !cursor.is_empty() { + return Err(RuntimeError::Decode(format!( + "{} trailing bytes; metadata does not match this extrinsic", + cursor.len() + ))); + } + + let (pallet, name, args) = self + .dispatch_of(&call, &mut accounts) + .ok_or_else(|| RuntimeError::Decode("call is not a pallet dispatch".into()))?; + + Ok(DecodedExtrinsic { + index, + version, + signed, + signer, + signature, + signature_bytes, + pallet, + call: name, + args, + extra, + accounts: accounts.into_iter().collect(), + }) + } + + /// Decode one registry type off the front of a cursor, naming what failed. + fn decode_at( + &self, + ty: u32, + cursor: &mut &[u8], + what: &str, + ) -> Result, RuntimeError> { + scale_value::scale::decode_as_type(cursor, ty, &self.metadata.types) + .map_err(|e| RuntimeError::Decode(format!("{what}: {e}"))) + } + + /// The account behind a `MultiAddress`, when it is a plain id. + /// + /// The other forms — an index, a raw 20 bytes — name an account the chain + /// resolves later and this cannot, so they are `None` rather than a guess. + fn sole_account( + &self, + address: &scale_value::Value, + accounts: &mut BTreeSet, + ) -> Option { + let rendered = self.normalise(address, accounts); + // `normalise` unwraps a single-field variant to its inner value, so a + // `MultiAddress::Id(AccountId32)` arrives here as the hex string. + match rendered { + serde_json::Value::Object(map) => { + map.get("Id").and_then(|v| v.as_str()).map(str::to_owned) + } + serde_json::Value::String(s) if s.starts_with("0x") && s.len() == 66 => Some(s), + _ => None, + } + } + + /// Pull `(pallet, call, args)` out of a `RuntimeCall`. + /// + /// The same two-deep enum shape as an event: an enum of pallets, each of + /// which is an enum of that pallet's calls, both named by the runtime. + fn dispatch_of( + &self, + call: &scale_value::Value, + accounts: &mut BTreeSet, + ) -> Option<(String, String, serde_json::Value)> { + let scale_value::ValueDef::Variant(pallet) = &call.value else { + return None; + }; + let inner = match &pallet.values { + scale_value::Composite::Unnamed(v) => v.first()?, + scale_value::Composite::Named(v) => v.first().map(|(_, v)| v)?, + }; + let scale_value::ValueDef::Variant(variant) = &inner.value else { + return None; + }; + Some(( + pallet.name.clone(), + variant.name.clone(), + self.normalise( + &scale_value::Value { + value: scale_value::ValueDef::Composite(variant.values.clone()), + context: inner.context, + }, + accounts, + ), + )) + } + /// Everything this runtime says about itself. /// /// The metadata is already in memory for decoding; this is the same @@ -1013,6 +1262,87 @@ mod tests { assert_eq!(target.value.as_ref().and_then(|v| v.as_u64()), Some(12_000)); } + fn extrinsic(hex_str: &str) -> Vec { + hex::decode(hex_str.trim().trim_start_matches("0x")).expect("fixture is hex") + } + + /// A real mainnet transaction, decoded with nothing but the registry — + /// including a post-quantum signature no Substrate decoder has heard of. + #[test] + fn a_signed_extrinsic_decodes_down_to_its_arguments() { + let rt = Runtime::from_metadata(&metadata()).expect("parses"); + let xt = rt + .decode_extrinsic( + 1, + &extrinsic(include_str!("../tests/mainnet-extrinsic-signed.hex")), + ) + .expect("decodes"); + + assert!(xt.signed); + assert_eq!(xt.version, 4); + assert_eq!( + xt.signer.as_deref(), + Some("0x9f8849227d2de5f0f480c76a996bb964435a942030890cab12b3b91a99f8443b") + ); + // The scheme by name, and the size that makes storing it a bad idea. + assert_eq!(xt.signature.as_deref(), Some("Dilithium65")); + assert!(xt.signature_bytes > 4000, "{}", xt.signature_bytes); + + assert_eq!(xt.pallet, "Utility"); + assert_eq!(xt.call, "batch_all"); + + // The nested calls are reached without any case for `batch_all`: the + // registry describes a call inside a call, and `normalise` walks it. + let inner = xt.args["calls"].as_array().expect("batch carries calls"); + assert!(inner.len() > 1, "{inner:?}"); + let first = &inner[0]["Balances"]["transfer_allow_death"]; + assert_eq!(first["value"].as_u64(), Some(589_105_986_180)); + + // And every account in those nested calls is collected, which is what + // puts a batched transfer on its recipient's page. + assert!(xt.accounts.contains(&xt.signer.clone().unwrap())); + assert!( + xt.accounts.contains( + &"0xa56109a3522189b14376cd562492b220d178578d81d09d737b74c9f4f394f31d".into() + ), + "{:?}", + xt.accounts + ); + } + + /// The preamble byte's top two bits are a type tag, not part of the + /// version. Mainnet's timestamp inherent is `0x05` — bare, version *5* — + /// while the metadata declares extrinsic version 4 and signed transactions + /// say `0x84`. Reading that byte as a version and checking it rejects every + /// inherent on the chain. + #[test] + fn an_inherent_is_bare_and_its_version_is_not_the_metadatas() { + let rt = Runtime::from_metadata(&metadata()).expect("parses"); + let xt = rt + .decode_extrinsic( + 0, + &extrinsic(include_str!("../tests/mainnet-extrinsic-inherent.hex")), + ) + .expect("decodes"); + + assert!(!xt.signed); + assert_eq!(xt.version, 5); + assert_eq!(xt.signer, None); + assert_eq!(xt.signature, None); + assert_eq!(xt.pallet, "Timestamp"); + assert_eq!(xt.call, "set"); + assert!(xt.args["now"].is_number() || xt.args["now"].is_string()); + assert!(xt.accounts.is_empty()); + } + + #[test] + fn a_truncated_extrinsic_is_refused_rather_than_half_read() { + let rt = Runtime::from_metadata(&metadata()).expect("parses"); + let full = extrinsic(include_str!("../tests/mainnet-extrinsic-signed.hex")); + let err = rt.decode_extrinsic(0, &full[..full.len() / 2]).unwrap_err(); + assert!(matches!(err, RuntimeError::Decode(_)), "{err:?}"); + } + #[test] fn a_block_decoded_against_the_wrong_runtime_fails_loudly() { // Trailing bytes mean the registry and the data disagree. Storing a diff --git a/crates/blackbeard-core/tests/mainnet-extrinsic-inherent.hex b/crates/blackbeard-core/tests/mainnet-extrinsic-inherent.hex new file mode 100644 index 0000000..01f3e3d --- /dev/null +++ b/crates/blackbeard-core/tests/mainnet-extrinsic-inherent.hex @@ -0,0 +1 @@ +0x280501000b86556786a001 \ No newline at end of file diff --git a/crates/blackbeard-core/tests/mainnet-extrinsic-signed.hex b/crates/blackbeard-core/tests/mainnet-extrinsic-signed.hex new file mode 100644 index 0000000..ff56064 --- /dev/null +++ b/crates/blackbeard-core/tests/mainnet-extrinsic-signed.hex @@ -0,0 +1 @@ +0x655784009f8849227d2de5f0f480c76a996bb964435a942030890cab12b3b91a99f8443b01d4b98bb00faf377b05490ae787228ddd640938f581c6151eed9b81ae777026186d178df1692c458ce9f42ad25a77cdf232533c6df45437faa4a3b436500727bc08a3aeabcb61509b52f6b7edbc49ba288b7dbd9a75a9a66e70a6e02c08953cf3ef13d06095ed7d855c7c57742e0aed3548c6f1d168872c3deb1f1df236fd82c4db3848743ee791c3eb6aef0d3c9e1e7c7ce1462f88cfef4f475dc5d04498c2ea3323af8f8554cac88c6941d6443df5d21ea90155822a4efc7fac9b449726ad28030989b29ae1b996439a4309d66368e85f411411e4d22338c36e9d1130b9b18fec823fe20e7f674489e48eca7767920844453f2faebc6b82c0f62844ea826454fec233f45ba3f9ee0b3abbfec1a86af361bbb1d455cfd5eb6be6fe242d212253fba5d2f8240ec07de5b8a20a89b40cddfb33fb5657fc97dcb9fd09ef5d39f598e4c81c6fbbb79da56b91957b56f4434724ee2008cf4aa83b5ff6f26f2ca5ffd7d48ecd09a37374b53561d26b54b412f5d063f45a2a7614d6ce65d857abda2dbfc061ca436b60ca9e038954ad82f4fe6981baa45bb9996a653f4c70e662e1c97be602ef5d2fb3b452cdb79af5b0dbfe48670e6e96dfb698a0a48cbdb1649939220efd783ec62ac59a8ff024b458064c7aaf76a2fcb79744f64f92a96e24438b799add7edbefbea970e2eb0a0e9cbc6a87d00b900f7856809ab1278be7f66a77ef88d6728c563641c6f03ab2714c74e7c2e0c4518f11938a1b77fb89586c93f37064b3ea86cce40a76c22416c17163211c94ff9017e133e5bfdc2d5b5236efe27c3c2d4f625e88db36db06491f80f71c0fd13729e7449c23f67b7825ae5eb1607aed0d6184cb59d8e4d74ef34aa344da0711c378aa6e3f491c60b46f2cdb0ce8609c494c39b0c0bdcb5de531e7d755905c8a76ee0d780b7bab10c61df70e382ad72b2698040cb80884a4c8d847179af4cdf6c1fe8b1073d016935048cdc61d443f85b4846baa6e95c3f915be162864bd1025c29e7422044dd20e1e45ea68165d2d3bf1d43223a7f1013ee841e2aaccf860496ed75d6f75d4639f983c989a689df3918cb0f16b671dd7aac023b38a1b35e8a5829684cc8e280beec581baecaab4c8b3314b2142661b473c8bb843c877ff3b7681aa5898ef0d20dd499520e03d0918e3e53cabbba9b81ed972410e76fbcdb6d7e1467bf1a0ba8023b3f9ea09b5d0a7a7bdcb95384950b081af1bbe95e55f20c7e82c67d4a137ee8fcfc1661ca9b5435f72deb388fc6c699591209ca10963445529ef743c3152a8f5340e48a8295a3c1ec2135f02492a4bacb1ee7cb561281cdcaacd739729810622e6de1dab3619695c263bf27c073a0ba540d6e696e6c4919cdabccd7d1d3c6a6f810c53fc75181c1e2039ceb35a2dc946df7fecf8a4f05fd9f5cc372a1066e2e900ff1423a55b5de949bab3824d976081bc80481e747ff909cd576bec5225702270eb7196b92d60e22b7e6ec9d704bd84f9a272f2f14781e63e6554162d5326fc2cc6cb71ab996ba0d4ec7ab0323e06147d3af6c9748331367e52900b95415394f17f70224bef06674e1bb1baa22c13fbc3d5a7d2f848f6aca967fcde2afdc955392a2e704f4255d8ebbcb1f6f362ec0b07c7896227505deef9d4d47fa5e5873eb16a34ccb2d8fc67daa0c2f5e6a944b8a41a670f019e5acd8d939b25d5c6a883ed95c75b87d54bdbf64d8d72160a8da342dcafae19764c7d1db1c3683b4d5774c5e4f90256883a617321bb3b2fab174e2fb8680eb57b50a3107a4e7e66e8c573175e874ac65971adcda5573c13f44a1b2675bc088ad2142607a746f40d637b03a0064cf42cced99988b7ad62d2f2f97f006b93e58a7241c2ff3014a8d63cb93c12969da3b611fff8109b2854ea0e7dbc51a56ce9e15275adbd3fbc99bc211cbe0a0702b790de7533a2688f86a1275026d68349b0eb3e7fddfa47e5298950251a9caaaca4293e64bf8c501d64bfa0ae4219bb067efa6edfd4944696b152b3387e91d8edafa32dafad5e38cc3f3b667063e89bc710abb0895cc278fe48dc49e2d67eca6aa59e4b52f0152301dafd460bfd2aa27a2123b9f42951f9bd89ff0333d5442ab9fe3b87070f6d9918a8bca5fa22a39ac867c33e054fc19700ef278b550f35e89c4af58cb6079cadb3fa8271c891b1afcc1b8e0963054362c77058b67e6db23f7b173c9de5cb8593a03065041d68c5c0ca0a7e8653a63620d6d9ca56d3dbba60080f80aedd9be9a0d42580045a32eadb7cb20238eea62cb0b42450b7768023380586f3468fd00014d9e4d668dbd0f0c15e74ff720680bb54293cf36065c87c78df0722fa5b370d35fe130792883f41c7f80efca57dd828e0bbf14949054554b108d0e5d6fd7235cef3d2a9e0212afc50f3e01c497fd83e0cb994f8bd19267ca893c45b082bf6b90bc851677b7be553cbee91fcdd230eec36af86e7ba37225c5045e5d235216f41e767eda58672d4de391a8ad408cfa7ea0f6dda8fa2752d5f76fc02c4289c883964ec9d8415a8ded033a350b1c6f69337f2f85ad341e132bc4815c7a52329446b03726f6e63d68a24b03b04e95777e7c7385d4a506cff33db6bc85faa5fda66df3a5eba05f036ced531f6df18eadd680261719b5508ee2397a2f0cb54c183803c56ba42e661f0d8cb99cb7b851bb3c885a0745d08ddbb26a0ccd6c2d44986cb97192f214dbb71da1b5f1ed92e832aea44d02f97d53ecda1dd9dfcce56827f52fb1925edede6150a5aa5c10daa9b698c3a07f059ded100f629a9df0cc41d5ab04f39120233b43c9e6d4c5ac8f8b352b1c987d057a55b1f7d05733673dab269358042a1aca3ff4f7c45b83d0cb1a22d9fc81ac35f628979d6f881fe50e0e4ebf2f0f9e1985046f87548f10c09442c61353c9eb9667ed4175688f6006d555dc0d05fb14c412001aa00beaa76a8a046224e932b95f40eb56d242b3713e471d9b4a49914d07de1ebd3a82ac2038a3ca4d19a83e70590d9dd3a536421d1da20d4239fba20c7d78b02d01ae949197615aa1a975b241b3781322aee44eb699739f93bd12d0476dcf695c26dc8c166b20b9d6316414a218cad6fbfb34a140bb95a5d9908374e723cdd91ae7934c7a598dc7123a25879a0f807f0a030015562d4c087e73931ebc2bd9f74329c0200786b00bd4c21ddaf86ebe6d2ef3dad7e71e01be54b872ce2f615ec3ef445b3d4b635c1fc134c97fefa31a0390af842b3188abe05fece82ce84aa1a76d126e9fb5ba6bb7ad23740c42c0b94073724d9407e6c5c38be1ffa05af3e093e4815ffdb71df9ffbe9563083e5b3069f179e6b75f82be2052d27c69fccd1defeb3bd1ddc95b7e004e52e73a1d3a2ba317d6bffd05c319b4819f6b13befda944c1543f2171eea167553370278c49531c3ade45292796d48bbeea4034e771cf1eea2997ef6478df4e593f09f96cd6f66440c87b1a0476237da05f6e57e55991d4c834d6777379c0d3bde6e2be72c714bcd2f056a60b01426536b261b663b4ca137561b6c96b4f31e8ef949bdca5282411f283d544bb81f7b78b0117be363b24e6d67e9ed3dae0311d3e43e4e3082585b740ffeb75d9adb2b2aa9f4dccbace78d92690a4cf1b3cba89d50bae939d7edbd3b806d926bf98fa8561d69cc35168a231dec7b35a4b616e6b9b10b86af693d866333d6315358dd682adb7c689cd510dd34040dce5e3fad97b33889862480d75626eb88358a1c9bcaca2ccc995ca2f2ccff8fe267e413efe4acb06f31d3562cea09b976d498ddcf4a41ab331189c4f0f7ee7eadefcfe8aa8d2f9164070bb587be44e5d2190c6cd9f9e8fed7439acab4bfac93695c6f4e0d7cf86f69790e5da0f0fa9dd082ed220f45e3997b9e7b825c2aa79f5ee97866fdadb261db735421b29f2efdb3e8b15b5fbe64fa9e79520e682e7ee1863b0f8242710d1d31d3eaee1b279c1bf94822959bd3769210a00d1afae4569326c6d96d183bb9cbb01d2fedcb6d592488cd1825ac32ac213798f7c615c74388ea1fd952ccc5a2bb62e8d088b1a753a629a16d24ec69c948c3f8d30292b085f8934f9eece5917007a4f8d9b1099af8db81540241bb99cd3949b8fb45c4c8febe6e8f44502d9af9c3323bc099ba23ec407b7bfaf38454f4dc35ba0376a021ea1a4303cdc1d3a602adc0a4ad45b18d19f7f065ef6ac4f483bb1c9a33ffc2601eb664b2f6ea8d677f1523cbd859221f3a0b0f39a6dbb640785fbb85d87f705ba142d4814c2fe3f424918d0337ff3320cce872a26f28b123d9a261bc356175597a9e0c292c98274750b8527589b7d6ab3740a5ab5020bd233e6964ddb46395e3060b79173710a0a7ccc902fdc9cc81324b118a5e5161251d20dd2203f4e4f76afcd3c84da151bcebad58a04c2398ada358f888916b23378b912ba0fc3f4e0ce7a03490895cd38317020b6f00b02031167e89e06f6359a3b1116bb9362c34de2b43978104b1df28fdd180ecb57dc4cab4a4f77f004e8a02d652e2e23a0a40a4a380f8918e5194db2f47560947f7f0ea266b41ecdc716c584c3f35efa60cb19916f16ab37298989bea71550b1f54797b8e90d6e0f519222b3c3e6265a7979ad7f4b5cef4001a2870313763b0b3d2d3e6f700000000000000000000000000000000000a1216191d265519ca05e8cb1f72305731a8c7fd2268ec3eff19e65baf8b567581d364820e619e217f2bb286aba93f693e09c56b8a8ba884e03e969880cbea1fca9adf7c91902c427744440f1e6c79227f6b0c94e6bd1cfb05b3b4e7d4d14945988aa8e7e729023a71239fbcf8c7a4b5603eaff62043286cc9986775da5cf399c30e8a35c8f6a2349b19e2c754d2c9a3956fd729c70e2f567c29f1d717d83264ca45d91aa520ade67d8ec09bd78d355f4f1348e5be7ee931b819467096f3d91759468249edd1dd2d3a017bc601a1ffd7552e75eacd5a754bc1ddab433b2f51e2b1c5d9728df748387ba95977b29f308cec5d3d7532637c2fa49486c22d3bc1593e9a6ba59fa8fee4bba7c0d1c64070add9282fe2f391b77b0da53737ace22838358011e59a3e970fe9d922a1129d55317f41a9bcce1343b16c55fb536f00e2c533639cbfd72337cab84c60f019025ecfa34a96774ffac106e3e9936db322acc5dcd707f6fc157e5c74e417ae8bbbad8d526dd2a0d1c552aeb5b934f7111a0932d8ba6e04da413a1250fcaa86b9200fbd9c3b473aa8db4591e459b9d1e0f562256398691ee74afb2789887429b6c8743222741937367e418de7693b7d5d6dfc577debdb2d36a6f1851b139a78185ebf7ea7e5e8c94f6d2b773004b9392c84723fe953148536f9ca6370efd53c1fbb1275ee0d156fd1b45c793851f048b46485cf5ae74cbfe882fc634db833c9398782ada3040543219430ca79cb35c2128b589575e453864771ad97821217888cefd06b7326c2444f2957e9e68e84da04b3ac571d99ac13fa675932a9f8dff7e5d3da1a286faaa97fa5a78243cd6b04ba4f28ea9301683477ee4d113215268b6be65237aa30145adfcb4e38a8e456e8ac0f80b009f5476c1c0cc2faa122bb9000b4aff24684c62738cd4ad52f0d3b83037d6d9fa2ac75c34ca31349b49c734f9cdf242e5030097f21ee2538b0a83f68fe14f1c913835689e64481885e2fd657f4802f10e6d42874e7370b8dee2412ecd585ab384612f982ec9d1cefaa0997a5818eb7769c1d32a5071dca67156e04cd354fafbe65b8d83356427358636eba77bd423e4b64e464995da18077ff154853f732318492fda10330215cc03487d15c6b4248e102fc85ac4a125b9cc201a75ca4690b5bbadab08d2387d1f8a73615260b2040a4095e16991de00f248e29bc16958ebfe7edb068721f162427ec43d133530f27b18202b69e71d967a86094679c6f27f672b218ceee61e500f96b96825463f727d19c1a5531581918579f9bee0fdd3af1e15377f10b3b4b40502c1ba275bf1e1573215842e3ca5de04f377ae4491c25d209ac43868a6b6c7e20dde6dbf4aa3c55e1e37248928355b4b1b18d58e3eceac96ae9693bef0667eb03ec919288ff7d4773ab0b6f6e046e22812a5d49e230d2d611e761c3fd88eced02332b4a9ce1540c3fa97e9c29ea966ee58045e72db02a0cfdba3f81f320cddab3ee3410cc89d6b98c5ab1a772c2f925b0be0f697b072476c938287f08e264460813c7ab9200a35e80a08e903624d9dce2de09f3b9619949d4f87661f9336b5104270d23f62e5f87a514524570b099738ad6304037e653415013a4bd823fb438cec8557d6874578e7d6a7297de931bb03988f5a6380aef80eb48af901c2fac90ea3a3a38281454abe146b9f6d2158374153cbc4fcc61d52872f61731e1c42941ff7298c619b96fa4ed739a69101c9817cb2b2fc27093338645c0835a46b898b8a86b0c2a2dc7be9032fa8adf7dc447f78978192b61da5390b2002491832e87405deb09e9fdf50f3137e5548d533f410d32ca1ea5567a5d1564592a0e48e5ce40650f2c1fecbb4e9e623800e85afa9f7dde2e786820730c8380b4429da04562659f26ac1fc8f8ac1ca31fd24df6af63955be720fd399cedcbb3aab7b04724fb9a375f7355f7b79ad3314117a05328a49c84346fd916064c3c36c78d1191da34dd5c392d32fe658cb0cbf83e90cff0b137503cf2066576839b8fe78b63cd67d146cb4224b265594a8ae083e6ac6733c0095d58b36326eff576b8f52247fc0ccf40a1c42c27489b9bddd5a1e543ee876465c13286b7f6cadc00ef3ac39a05e0b16b0ff563e74d33d00a4b7fd5910a23b4b300e911dbc26a515db7961cf8a74496b70d783fe1a60a6d99519e3e742fadf6d1497b66bb6bce87d0a316efac5695f238ad1a46c15ff9b80023e3ecf80a45b966f4bb5ef6cd613d59c9907415f3a266409681d1d98820e5e839168b87cd29e07c2e37f55417419901d2175f7d365e0ec0aaf058faddd8d932e183aa2668f47cfc277f86076d486689df546529b8902ad657c511ca5b21106bc9e5619c3451f4f8da8599c5c8a35052fbb36070a446bb19f8ab1f4d010eb6475572fd446c00b1506f59c0097d9936e13220c3933fcb85b26a4cdc2cb8fe6e028edddd79c5f9a36303f1613a6a1e92845750a940067f9b2f9ec519e4727874de205775d06fe81dd2939ae52f69ee3850bd85db6ba2d0d09e473d54be723a42f41e0aaefae58ecb4779b13a9295252f45670df7aca6254d6cca8fc18056f82259a0c9bdcbc4ee6314a9a1ccd463df5de86a60aa2ed601e6f994d4846d1c6d20009bccc0cc1561675cb4f744c62927e6dd14e6e053be85878bcbe9acacf12cbb7ad6a7b5d7731702aa17dc4cbef087101d946d8b06597510256911d47d546d77a1b2bf8a46f67fd72e743f5b8912b152863a4acb1420207c070d14000009021c020000a56109a3522189b14376cd562492b220d178578d81d09d737b74c9f4f394f31d0784fa732989020000d9467e117066e40ea156f5884d3d5d70ce91fb02eeb4cffbb2a89be951ce38c40b1f98a60a15020200006c7d2b2bcec4b7885c524ea6dfad39b4b257d4a3f829bab4ddc44168b6bc14bf0be6fc8f32a30102000068bd185151aa567d9c83eb42fbe9cefc474f82beded9a99d9e0f6b99a893954b07e62da2e9e4020000a86791335dfa56de909112170d6b602c404d54d32118f7e61f8095fb2452d18c0707c5a34281020000ab872c57ca31b368b98cea4d0a4416d36e8495bbec78f70ead9946a8baa051e607ee67b894b5020000c01cdb2ede675602372aa6da1128a55d93256ec717b64c29523d7b5dfebe8c3207bf54a987f5 \ No newline at end of file diff --git a/crates/blackbeard-data/migrations/0006_extrinsics.sql b/crates/blackbeard-data/migrations/0006_extrinsics.sql new file mode 100644 index 0000000..2607fcd --- /dev/null +++ b/crates/blackbeard-data/migrations/0006_extrinsics.sql @@ -0,0 +1,61 @@ +-- What people asked the chain to do, as opposed to what it then reported. +-- +-- ## Why this is a second table rather than more rows in `chain_event` +-- +-- An event is the chain's account of what happened; an extrinsic is the +-- request that caused it. They answer different questions and have different +-- shapes — an extrinsic has a signer, a nonce, a tip and a fee, and an event +-- has none of those — so folding them together would mean a table where half +-- the columns are null for half the rows. +-- +-- They share the parts that make a per-account view work: `accounts` filled by +-- the decoder, and a `jsonb` payload in the runtime's own vocabulary. That is +-- what lets one query merge both into a single history. +create table chain_extrinsic ( + chain text not null references chain (id) on delete cascade, + height bigint not null, + -- Position in the block's body. With the height it is the natural key, it + -- makes re-indexing idempotent, and it is what an event's `ApplyExtrinsic` + -- phase points at — the join between the two tables. + extrinsic_index integer not null, + pallet text not null, + call text not null, + -- Null for an inherent: the block author inserted it and nobody signed it. + signer text, + -- The signature *scheme*, by name, never the signature. + -- + -- A Dilithium signature is 5.3 KiB. At a block a second that is gigabytes a + -- month of bytes no page renders and no query reads. It is decoded during + -- indexing because that is the only way to find where the call begins, and + -- then thrown away; the size is kept because it is the single most + -- surprising fact about a transaction on this chain. + signature text, + signature_bytes integer not null default 0, + -- Call arguments in the runtime's own names. Nested: a `Utility::batch_all` + -- carries entire calls in here, which is why an account can be the + -- recipient of a transfer that is not its own top-level extrinsic. + args jsonb not null, + -- Mortality, nonce, tip — the signed extensions as submitted. Null for an + -- inherent, which signs nothing. + extra jsonb, + -- Whether the dispatch succeeded, from the `System::ExtrinsicSuccess` or + -- `ExtrinsicFailed` event with this extrinsic's index. Read from the events + -- already decoded for the block rather than stored as rows of their own — + -- two per block, every block, for one boolean. + success boolean, + accounts text[] not null default '{}', + at timestamptz, + primary key (chain, height, extrinsic_index) +); + +-- "Everything involving this account", the same shape as the event index, so +-- the merged history is two index scans rather than a scan of either table. +create index chain_extrinsic_accounts_idx on chain_extrinsic using gin (accounts); + +-- "This account's activity, newest first", and "this block's extrinsics". +create index chain_extrinsic_recent_idx + on chain_extrinsic (chain, height desc, extrinsic_index desc); + +-- "Every transfer", "every batch" — the call-kind feed, matching the event +-- index's equivalent. +create index chain_extrinsic_kind_idx on chain_extrinsic (chain, pallet, call, height desc); diff --git a/crates/blackbeard-data/src/rpc.rs b/crates/blackbeard-data/src/rpc.rs index d15c355..776a085 100644 --- a/crates/blackbeard-data/src/rpc.rs +++ b/crates/blackbeard-data/src/rpc.rs @@ -78,10 +78,13 @@ pub struct RuntimeVersion { } /// A block body, reduced to what the observer reads from it. -#[derive(Debug, Clone, Copy)] +#[derive(Debug, Clone)] pub struct BlockBody { - /// Extrinsics in the block, inherents included. - pub extrinsics: u32, + /// The block's extrinsics as the node returned them, `0x` hex, in order — + /// inherents included. Kept raw rather than decoded here: `blackbeard-data` + /// does I/O and `blackbeard-core` does decoding, and the runtime needed to + /// read these lives on the other side of that line. + pub extrinsics: Vec, /// The author's timestamp from the `Timestamp::set` inherent. pub timestamp_ms: Option, } @@ -267,7 +270,6 @@ impl RpcClient { return Ok(None); }; Ok(Some(BlockBody { - extrinsics: extrinsics.len() as u32, // The timestamp inherent is always first. A body whose first // extrinsic does not decode as one costs this block its timing and // nothing else. @@ -275,6 +277,11 @@ impl RpcClient { .first() .and_then(Value::as_str) .and_then(blackbeard_core::scale::timestamp_inherent_ms), + extrinsics: extrinsics + .iter() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect(), })) } diff --git a/crates/blackbeard-data/src/store.rs b/crates/blackbeard-data/src/store.rs index 3a645a7..a18060e 100644 --- a/crates/blackbeard-data/src/store.rs +++ b/crates/blackbeard-data/src/store.rs @@ -180,6 +180,92 @@ pub struct StoredEvent { pub fields: serde_json::Value, } +/// One row of an account's merged history. +#[derive(Debug, Clone)] +pub struct ActivityRow { + /// 1 for an extrinsic, 0 for an event. Part of the sort key, and what tells + /// a reader whether they are looking at a request or a result. + pub source: i32, + /// Block it belongs to. + pub height: u64, + /// Position within that block's extrinsics or events, per `source`. + pub index: u32, + /// Pallet, as the runtime names it. + pub pallet: String, + /// The call or the event variant, as the runtime names it. + pub name: String, + /// Call arguments or event fields. + pub payload: serde_json::Value, + /// The block's own timestamp. + pub at: Option>, + /// Who signed it. Extrinsics only, and `None` for an inherent. + pub signer: Option, + /// Whether the dispatch succeeded. Extrinsics only. + pub success: Option, + /// When in the block an event fired. Events only. + pub phase: Option, + /// Every account this row mentions, as `0x` hex. + pub accounts: Vec, +} + +/// One decoded extrinsic, ready to store. +#[derive(Debug, Clone)] +pub struct ExtrinsicRecord { + /// Which chain. + pub chain: ChainId, + /// Block it was included in. + pub height: u64, + /// Position in that block's body. + pub extrinsic_index: u32, + /// Dispatching pallet, as the runtime names it. + pub pallet: String, + /// The call, as the runtime names it. + pub call: String, + /// The signing account as `0x` hex; `None` for an inherent. + pub signer: Option, + /// The signature scheme by name, never the signature. + pub signature: Option, + /// How many bytes that signature took. + pub signature_bytes: u32, + /// Call arguments, normalised. + pub args: serde_json::Value, + /// Signed extensions as submitted. + pub extra: serde_json::Value, + /// Whether the dispatch succeeded, when the block's events said. + pub success: Option, + /// Every account it mentions, nested calls included. + pub accounts: Vec, + /// The block's own timestamp. + pub at: Option>, +} + +/// One extrinsic read back. +#[derive(Debug, Clone)] +pub struct StoredExtrinsic { + /// Block it was included in. + pub height: u64, + /// Position in that block's body. + pub extrinsic_index: u32, + /// Dispatching pallet. + pub pallet: String, + /// The call. + pub call: String, + /// The signing account as `0x` hex. + pub signer: Option, + /// The signature scheme by name. + pub signature: Option, + /// Bytes that signature took. + pub signature_bytes: u32, + /// Call arguments. + pub args: serde_json::Value, + /// Signed extensions as submitted. + pub extra: Option, + /// Whether it succeeded. + pub success: Option, + /// The block's own timestamp. + pub at: Option>, +} + /// One account's mining income, for the ranked list. #[derive(Debug, Clone)] pub struct AccountRanking { @@ -1113,59 +1199,196 @@ impl Store { Ok(()) } - /// Everything involving one account, newest first. + /// Persist a block's decoded extrinsics. Idempotent on `(chain, height, + /// extrinsic_index)`, so re-indexing a block rewrites rather than doubles. + pub async fn record_extrinsics( + &self, + extrinsics: &[ExtrinsicRecord], + ) -> Result { + if extrinsics.is_empty() { + return Ok(0); + } + let chains: Vec = extrinsics.iter().map(|e| e.chain.0.clone()).collect(); + let heights: Vec = extrinsics.iter().map(|e| e.height as i64).collect(); + let indexes: Vec = extrinsics + .iter() + .map(|e| e.extrinsic_index as i32) + .collect(); + let pallets: Vec = extrinsics.iter().map(|e| e.pallet.clone()).collect(); + let calls: Vec = extrinsics.iter().map(|e| e.call.clone()).collect(); + let signers: Vec> = extrinsics.iter().map(|e| e.signer.clone()).collect(); + let signatures: Vec> = + extrinsics.iter().map(|e| e.signature.clone()).collect(); + let sig_bytes: Vec = extrinsics + .iter() + .map(|e| e.signature_bytes as i32) + .collect(); + let args: Vec = extrinsics.iter().map(|e| e.args.clone()).collect(); + let extras: Vec = extrinsics.iter().map(|e| e.extra.clone()).collect(); + let successes: Vec> = extrinsics.iter().map(|e| e.success).collect(); + let accounts: Vec = extrinsics + .iter() + .map(|e| serde_json::Value::from(e.accounts.clone())) + .collect(); + let times: Vec>> = extrinsics.iter().map(|e| e.at).collect(); + + let result = sqlx::query!( + r#" + insert into chain_extrinsic + (chain, height, extrinsic_index, pallet, call, signer, signature, + signature_bytes, args, extra, success, accounts, at) + select chain, height, extrinsic_index, pallet, call, signer, signature, + signature_bytes, args, extra, success, + array(select jsonb_array_elements_text(accounts)), at + from unnest( + $1::text[], $2::bigint[], $3::int[], $4::text[], $5::text[], $6::text[], + $7::text[], $8::int[], $9::jsonb[], $10::jsonb[], $11::bool[], $12::jsonb[], + $13::timestamptz[] + ) as t(chain, height, extrinsic_index, pallet, call, signer, signature, + signature_bytes, args, extra, success, accounts, at) + on conflict (chain, height, extrinsic_index) do update set + pallet = excluded.pallet, + call = excluded.call, + signer = excluded.signer, + signature = excluded.signature, + signature_bytes = excluded.signature_bytes, + args = excluded.args, + extra = excluded.extra, + success = coalesce(excluded.success, chain_extrinsic.success), + accounts = excluded.accounts, + at = coalesce(excluded.at, chain_extrinsic.at) + "#, + &chains, + &heights, + &indexes, + &pallets, + &calls, + &signers as &[Option], + &signatures as &[Option], + &sig_bytes, + &args, + &extras, + &successes as &[Option], + &accounts, + × as &[Option>], + ) + .execute(&self.pool) + .await?; + Ok(result.rows_affected()) + } + + /// One block's extrinsics, in body order. + pub async fn extrinsics_at( + &self, + chain: &ChainId, + height: u64, + ) -> Result, DataError> { + let rows = sqlx::query!( + r#" + select extrinsic_index, pallet, call, signer, signature, signature_bytes, + args as "args!", extra, success, at + from chain_extrinsic + where chain = $1 and height = $2 + order by extrinsic_index asc + "#, + chain.as_str(), + height as i64, + ) + .fetch_all(&self.pool) + .await?; + Ok(rows + .into_iter() + .map(|r| StoredExtrinsic { + height, + extrinsic_index: r.extrinsic_index.max(0) as u32, + pallet: r.pallet, + call: r.call, + signer: r.signer, + signature: r.signature, + signature_bytes: r.signature_bytes.max(0) as u32, + args: r.args, + extra: r.extra, + success: r.success, + at: r.at, + }) + .collect()) + } + + /// Everything involving one account, newest first — requests and results + /// together. /// - /// The whole per-account view, in one query, for every event type the chain - /// has or will have. `accounts @> array[…]` is answered by the GIN index, - /// and the list it searches is the decoder's own — so a pallet added next - /// year appears here without a migration, a struct or a query. + /// One query over both tables rather than two lists a caller has to + /// interleave. An extrinsic is what somebody asked the chain to do and an + /// event is what the chain then reported; a history that showed only one of + /// them would either omit the failed attempts or omit who made them. /// - /// `before` pages backwards: pass the `(height, event_index)` of the last - /// row seen. Keyset rather than `offset`, because new blocks arrive at the - /// front of this ordering while a reader is paging through it and `offset` - /// would show them the same row twice. - pub async fn account_events( + /// Ordered by height, then extrinsics before the events they caused, then + /// by position. `source` is 1 for an extrinsic and 0 for an event precisely + /// so that every part of the key sorts descending — which is what lets the + /// cursor be a plain three-part row comparison rather than a mixed-direction + /// one Postgres cannot express. + /// + /// Keyset rather than `offset`, because new blocks arrive at the front of + /// this ordering while a reader is paging through it and an offset would + /// show them the same row twice. + pub async fn account_activity( &self, chain: &ChainId, account_hex: &str, - before: Option<(u64, u32)>, + before: Option<(u64, i32, u32)>, limit: i64, - ) -> Result, DataError> { - let (before_height, before_index) = match before { - Some((h, i)) => (h as i64, i as i32), - // The tuple comparison below is inclusive of everything under this, - // which for the first page is everything. - None => (i64::MAX, i32::MAX), + ) -> Result, DataError> { + let (h, source, idx) = match before { + Some((h, source, idx)) => (h as i64, source, idx as i32), + // Above anything real, so the first page is "before everything". + None => (i64::MAX, i32::MAX, i32::MAX), }; let rows = sqlx::query!( r#" - select height, event_index, pallet, variant, phase, extrinsic_index, - fields as "fields!", at, accounts as "accounts!" - from chain_event - where chain = $1 and accounts @> array[$2] - and (height, event_index) < ($3, $4) - order by height desc, event_index desc - limit $5 + with merged as ( + select 1 as source, height, extrinsic_index as idx, pallet, + call as name, args as payload, at, signer, success, + null::text as phase, accounts + from chain_extrinsic + where chain = $1 and accounts @> array[$2] + union all + select 0 as source, height, event_index as idx, pallet, + variant as name, fields as payload, at, + null::text as signer, null::boolean as success, phase, + accounts + from chain_event + where chain = $1 and accounts @> array[$2] + ) + select source as "source!", height as "height!", idx as "idx!", + pallet as "pallet!", name as "name!", payload as "payload!", + at, signer, success, phase, accounts as "accounts!" + from merged + where (height, source, idx) < ($3, $4, $5) + order by height desc, source desc, idx desc + limit $6 "#, chain.as_str(), account_hex, - before_height, - before_index, + h, + source, + idx, limit, ) .fetch_all(&self.pool) .await?; Ok(rows .into_iter() - .map(|r| StoredEvent { + .map(|r| ActivityRow { + source: r.source, height: r.height.max(0) as u64, - event_index: r.event_index.max(0) as u32, + index: r.idx.max(0) as u32, pallet: r.pallet, - variant: r.variant, - phase: r.phase, - extrinsic_index: r.extrinsic_index.map(|i| i.max(0) as u32), - fields: r.fields, + name: r.name, + payload: r.payload, at: r.at, + signer: r.signer, + success: r.success, + phase: r.phase, accounts: r.accounts, }) .collect()) diff --git a/crates/blackbeard-entities/src/account.rs b/crates/blackbeard-entities/src/account.rs index 911f47b..9a3dd0c 100644 --- a/crates/blackbeard-entities/src/account.rs +++ b/crates/blackbeard-entities/src/account.rs @@ -110,28 +110,50 @@ pub struct RewardSummary { pub last_at: Option>, } +/// Whether a history row is a request or a result. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)] +#[serde(rename_all = "snake_case")] +#[ts(export, export_to = "ActivitySource.ts")] +pub enum ActivitySource { + /// An extrinsic: what somebody asked the chain to do. Carries a signer, and + /// may have failed. + Extrinsic, + /// An event: what the chain reported happening. + Event, +} + /// One thing that happened to an account. /// -/// Deliberately not a closed set of kinds. The runtime names its own events and -/// the decoder keeps those names, so a pallet added next year appears here as -/// itself rather than as "unknown" — which is the whole reason the index is one -/// table rather than one per thing the site happens to show today. +/// Deliberately not a closed set of kinds. The runtime names its own calls and +/// events and the decoder keeps those names, so a pallet added next year +/// appears here as itself rather than as "unknown" — which is the whole reason +/// the index is two generic tables rather than one per thing the site happens +/// to show today. #[derive(Debug, Clone, Serialize, Deserialize, TS)] #[ts(export, export_to = "AccountEvent.ts")] pub struct AccountEvent { - /// Block it fired in. + /// Whether this is a request or a result. + pub source: ActivitySource, + /// Block it belongs to. #[ts(type = "number")] pub height: u64, - /// Position within that block's events, which with the height is its - /// identity and what pages the list. + /// Position within that block's extrinsics or events, per `source`. With + /// the height and the source it is this row's identity and what pages the + /// list. #[ts(type = "number")] - pub event_index: u32, - /// Emitting pallet, as the runtime names it. + pub index: u32, + /// Pallet, as the runtime names it. pub pallet: String, - /// Event variant, as the runtime names it. - pub variant: String, - /// The fields, as the runtime names them. Accounts are `0x` hex and any - /// integer past 2^53 is a string. + /// The call or the event variant, as the runtime names it. + pub name: String, + /// Who signed it, as `0x` hex. Extrinsics only, and absent for an inherent. + pub signer: Option, + /// Whether the dispatch succeeded. Extrinsics only; `null` for an event and + /// for an extrinsic whose block's events did not say. + pub success: Option, + /// Call arguments or event fields, as the runtime names them. Accounts are + /// `0x` hex and any integer past 2^53 is a string. Nested: a + /// `Utility::batch_all` carries whole calls in here. #[ts(type = "Record")] pub fields: serde_json::Value, /// The block's own timestamp, when the node answered for it. diff --git a/crates/blackbeard-entities/src/block.rs b/crates/blackbeard-entities/src/block.rs index f7f7a75..df22965 100644 --- a/crates/blackbeard-entities/src/block.rs +++ b/crates/blackbeard-entities/src/block.rs @@ -1,11 +1,49 @@ //! Observed blocks. +use std::collections::BTreeMap; + use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use ts_rs::TS; use crate::{AttributionSource, BigUintDec, ChainId, MinerId}; +/// One extrinsic in a block, as the runtime describes it. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)] +#[ts(export, export_to = "BlockExtrinsic.ts")] +pub struct BlockExtrinsic { + /// Position in the body, which is what an event's `ApplyExtrinsic` phase + /// points at. + #[ts(type = "number")] + pub index: u32, + /// Dispatching pallet, as the runtime names it. + pub pallet: String, + /// The call, as the runtime names it. + pub call: String, + /// The signing account as `0x` hex. `null` for an inherent — the block + /// author inserted it and nobody signed it. + pub signer: Option, + /// That signer's SS58 address, when there is one. + pub signer_address: Option, + /// The signature scheme by name, e.g. `Dilithium65`. Never the signature. + pub signature: Option, + /// How many bytes the signature took. Worth showing: a post-quantum + /// signature is two orders of magnitude larger than the call it authorises. + #[ts(type = "number")] + pub signature_bytes: u32, + /// Call arguments, in the runtime's own names. Nested for a batch. + #[ts(type = "Record")] + pub args: serde_json::Value, + /// Whether the dispatch succeeded, per the block's own events. `null` when + /// those events did not say. + pub success: Option, + /// Accounts the call mentions, as `0x hex → SS58`, so a counterparty can be + /// rendered and linked without a second implementation of SS58 in the + /// browser. + #[ts(type = "Record")] + pub addresses: BTreeMap, +} + /// A block as the observer recorded it. /// /// Two timestamps, deliberately: `authored_at` comes from the block's own @@ -120,6 +158,14 @@ pub struct BlockDetail { /// Extrinsics in the body, inherents included. `None` once the body has /// been pruned. pub extrinsics: Option, + /// The extrinsics themselves, decoded, in body order. + /// + /// From this observer's index rather than from the node, which is why they + /// survive the node forgetting the block: the count above comes from the + /// body and goes with it, these do not. Empty for a block the index has not + /// reached — the backfill works outward from the tip — which is a different + /// thing from a block with no extrinsics, and the page says so. + pub body: Vec, /// Whether this hash is the one that currently holds this height. pub canonical: bool, /// The hash that currently holds this height. Equal to `hash` when diff --git a/crates/blackbeard-entities/src/lib.rs b/crates/blackbeard-entities/src/lib.rs index 76595d7..8aa1381 100644 --- a/crates/blackbeard-entities/src/lib.rs +++ b/crates/blackbeard-entities/src/lib.rs @@ -24,8 +24,8 @@ mod runtime; mod series; mod ws; -pub use account::{AccountDetail, AccountEvent, AccountRow, RewardSummary}; -pub use block::{BlockDetail, BlockObservation, RecentBlock}; +pub use account::{AccountDetail, AccountEvent, AccountRow, ActivitySource, RewardSummary}; +pub use block::{BlockDetail, BlockExtrinsic, BlockObservation, RecentBlock}; pub use chain::{ChainId, ChainInfo, ChainStatus, ChainSummary, ClientVersion, Tracking}; pub use error::{ApiError, EntityError}; pub use miner::{AttributionSource, LeaderboardRow, MinerDetail, MinerId, MinerSeriesPoint}; diff --git a/readme.md b/readme.md index 18239c0..02a1aed 100644 --- a/readme.md +++ b/readme.md @@ -190,6 +190,50 @@ become one decimal rather than four or eight little-endian limbs. Difficulty as `[1189189, 0, 0, 0, 0, 0, 0, 0]` is a correct description of the bytes and tells a reader nothing. +## Extrinsics: what was asked, not only what happened + +An event is the chain's account of what happened. An extrinsic is the request +that caused it, and it carries what no event does: who signed, what they +actually called, the nonce and tip they set, and whether it worked. A history +built from events alone silently omits every failed attempt and never names a +submitter. + +The same oracle does both. The metadata's extrinsic type carries four +parameters and the registry names all of them — `Address` is a `MultiAddress`, +`Call` is `RuntimeCall`, `Extra` is the twelve signed extensions, and +`Signature` is `qp_dilithium_crypto::types::DilithiumSignatureScheme`. That last +one is the part that would otherwise need hand-written post-quantum knowledge, +and it does not: the chain describes its own signature scheme, so +`decode_extrinsic` reads a Quantus transaction without a line of code that knows +Quantus exists. + +Two things about this chain's extrinsics are worth knowing before touching them. +**The first byte is not the version** — the top two bits are a type tag, and +mainnet carries `0x84` (signed, v4) and `0x05` (bare, v5) in the same block while +the metadata declares version 4. And **a signature is 5.3 KiB**, two orders of +magnitude larger than the call it authorises; it is decoded to find where the +call begins and then thrown away, with only the scheme's name and the byte count +kept. + +Both halves of a block are indexed in one pass, because both come from calls +already being made: the events blob for `chain_event`, the body for +`chain_extrinsic` and the block's own timestamp. Whether a dispatch succeeded +comes from the `System::ExtrinsicSuccess` and `ExtrinsicFailed` events in that +same decoded list — read, used, and not stored, because two rows per block +forever for one boolean each is not a trade worth making. + +An account's page merges the two into one history ordered by block, with the +extrinsic above the events it caused. `source` is 1 for an extrinsic and 0 for an +event precisely so every part of the sort key descends, which is what lets the +paging cursor be a plain three-part row comparison rather than a +mixed-direction one Postgres cannot express. + +Nested calls are the reason this is worth doing generically. A +`Utility::batch_all` carries whole calls in its arguments, so a transfer's +recipient can be three levels down — and because the decoder collects account +ids wherever it finds them, that batched transfer appears on the recipient's page +tagged *received* even though they signed nothing. + ## One account, from our own index `/quantus/account/qzp2AxZw…` answers what the official explorer does not: what diff --git a/web/src/App.tsx b/web/src/App.tsx index 895d868..38953d3 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -162,6 +162,8 @@ export default function App() { chain={chain} block={route.block} targetSeconds={info?.target_block_time_seconds ?? 6} + decimals={info?.token_decimals ?? 12} + symbol={info?.token_symbol ?? ''} onResolved={blockResolved} /> )} diff --git a/web/src/api/generated/AccountEvent.ts b/web/src/api/generated/AccountEvent.ts index b44bc38..841e469 100644 --- a/web/src/api/generated/AccountEvent.ts +++ b/web/src/api/generated/AccountEvent.ts @@ -1,34 +1,51 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { ActivitySource } from "./ActivitySource"; /** * One thing that happened to an account. * - * Deliberately not a closed set of kinds. The runtime names its own events and - * the decoder keeps those names, so a pallet added next year appears here as - * itself rather than as "unknown" — which is the whole reason the index is one - * table rather than one per thing the site happens to show today. + * Deliberately not a closed set of kinds. The runtime names its own calls and + * events and the decoder keeps those names, so a pallet added next year + * appears here as itself rather than as "unknown" — which is the whole reason + * the index is two generic tables rather than one per thing the site happens + * to show today. */ export type AccountEvent = { /** - * Block it fired in. + * Whether this is a request or a result. + */ +source: ActivitySource, +/** + * Block it belongs to. */ height: number, /** - * Position within that block's events, which with the height is its - * identity and what pages the list. + * Position within that block's extrinsics or events, per `source`. With + * the height and the source it is this row's identity and what pages the + * list. */ -event_index: number, +index: number, /** - * Emitting pallet, as the runtime names it. + * Pallet, as the runtime names it. */ pallet: string, /** - * Event variant, as the runtime names it. + * The call or the event variant, as the runtime names it. */ -variant: string, +name: string, /** - * The fields, as the runtime names them. Accounts are `0x` hex and any - * integer past 2^53 is a string. + * Who signed it, as `0x` hex. Extrinsics only, and absent for an inherent. + */ +signer: string | null, +/** + * Whether the dispatch succeeded. Extrinsics only; `null` for an event and + * for an extrinsic whose block's events did not say. + */ +success: boolean | null, +/** + * Call arguments or event fields, as the runtime names them. Accounts are + * `0x` hex and any integer past 2^53 is a string. Nested: a + * `Utility::batch_all` carries whole calls in here. */ fields: Record, /** diff --git a/web/src/api/generated/ActivitySource.ts b/web/src/api/generated/ActivitySource.ts new file mode 100644 index 0000000..c6a2b4b --- /dev/null +++ b/web/src/api/generated/ActivitySource.ts @@ -0,0 +1,6 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +/** + * Whether a history row is a request or a result. + */ +export type ActivitySource = "extrinsic" | "event"; diff --git a/web/src/api/generated/BlockDetail.ts b/web/src/api/generated/BlockDetail.ts index 511447f..08e91fa 100644 --- a/web/src/api/generated/BlockDetail.ts +++ b/web/src/api/generated/BlockDetail.ts @@ -1,6 +1,7 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { AttributionSource } from "./AttributionSource"; import type { BigUintDec } from "./BigUintDec"; +import type { BlockExtrinsic } from "./BlockExtrinsic"; import type { ChainId } from "./ChainId"; import type { MinerId } from "./MinerId"; @@ -88,6 +89,16 @@ seconds_since_parent: number | null, * been pruned. */ extrinsics: number | null, +/** + * The extrinsics themselves, decoded, in body order. + * + * From this observer's index rather than from the node, which is why they + * survive the node forgetting the block: the count above comes from the + * body and goes with it, these do not. Empty for a block the index has not + * reached — the backfill works outward from the tip — which is a different + * thing from a block with no extrinsics, and the page says so. + */ +body: Array, /** * Whether this hash is the one that currently holds this height. */ diff --git a/web/src/api/generated/BlockExtrinsic.ts b/web/src/api/generated/BlockExtrinsic.ts new file mode 100644 index 0000000..e147594 --- /dev/null +++ b/web/src/api/generated/BlockExtrinsic.ts @@ -0,0 +1,52 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +/** + * One extrinsic in a block, as the runtime describes it. + */ +export type BlockExtrinsic = { +/** + * Position in the body, which is what an event's `ApplyExtrinsic` phase + * points at. + */ +index: number, +/** + * Dispatching pallet, as the runtime names it. + */ +pallet: string, +/** + * The call, as the runtime names it. + */ +call: string, +/** + * The signing account as `0x` hex. `null` for an inherent — the block + * author inserted it and nobody signed it. + */ +signer: string | null, +/** + * That signer's SS58 address, when there is one. + */ +signer_address: string | null, +/** + * The signature scheme by name, e.g. `Dilithium65`. Never the signature. + */ +signature: string | null, +/** + * How many bytes the signature took. Worth showing: a post-quantum + * signature is two orders of magnitude larger than the call it authorises. + */ +signature_bytes: number, +/** + * Call arguments, in the runtime's own names. Nested for a batch. + */ +args: Record, +/** + * Whether the dispatch succeeded, per the block's own events. `null` when + * those events did not say. + */ +success: boolean | null, +/** + * Accounts the call mentions, as `0x hex → SS58`, so a counterparty can be + * rendered and linked without a second implementation of SS58 in the + * browser. + */ +addresses: Record, }; diff --git a/web/src/components/AccountPanel.tsx b/web/src/components/AccountPanel.tsx index 6e3ec26..7496954 100644 --- a/web/src/components/AccountPanel.tsx +++ b/web/src/components/AccountPanel.tsx @@ -22,125 +22,22 @@ import type { AccountEvent } from '../api/generated/AccountEvent' import { RequestFailed, fetchAccount } from '../api/rest' import { exactTokens, height as fmtHeight, shortAddress, tokens, when } from '../lib/format' import { href } from '../lib/routes' +import { Payload } from './Payload' -/** Field names that carry a balance, and so want the token treatment. */ -const AMOUNTS = new Set(['reward', 'amount', 'value', 'fee', 'actual_fee', 'tip']) - -/** Human labels for the events the site sees most. Anything else uses its own - * `Pallet::Variant`, which is already the runtime's answer and not a guess. */ +/** Human labels for what the site sees most. Anything else shows its own + * `Pallet::name`, which is already the runtime's answer and not a guess. */ const LABELS: Record = { 'MiningRewards::MinerRewarded': 'Mining reward', 'MiningRewards::FeesCollected': 'Fees collected', 'Balances::Transfer': 'Transfer', + 'Balances::transfer_allow_death': 'Transfer', + 'Balances::transfer_keep_alive': 'Transfer', + 'Utility::batch_all': 'Batch', + 'Timestamp::set': 'Timestamp', } -function label(event: AccountEvent): string { - return LABELS[`${event.pallet}::${event.variant}`] ?? `${event.pallet}::${event.variant}` -} - -/** A 32-byte account id, which is what the decoder renders accounts as. */ -function isAccount(value: unknown): value is string { - return typeof value === 'string' && /^0x[0-9a-f]{64}$/.test(value) -} - -/** - * One event's fields, in the runtime's own vocabulary. - * - * The account this page is about is folded away: every row here involves it by - * definition, and repeating it in every row would bury the half that differs. - */ -function Fields({ - event, - account, - chain, - decimals, - symbol, -}: { - event: AccountEvent - account: string - chain: string - decimals: number - symbol: string -}) { - const shown = Object.entries(event.fields as Record).filter( - ([, value]) => !(isAccount(value) && value === account), - ) - return ( - - {shown.map(([key, value]) => ( - - {/* The key only when there is something to tell apart. A reward has - one field left once this account is folded out of it, and - "REWARD 0.31 QTC" in a column headed Detail says the same thing - twice. */} - {shown.length > 1 && {key}} - - - ))} - - ) -} - -function Value({ - name, - value, - chain, - addresses, - decimals, - symbol, -}: { - name: string - value: unknown - chain: string - addresses: Record - decimals: number - symbol: string -}) { - if (AMOUNTS.has(name) && (typeof value === 'string' || typeof value === 'number')) { - const raw = String(value) - return ( - - {tokens(raw, decimals)} {symbol} - - ) - } - if (isAccount(value)) { - // The counterparty, in the spelling they would recognise and as a way to - // their own page. The raw id is kept in the title, because it is what the - // chain actually stored and what anyone checking our working needs. - const address = addresses[value] - if (!address) { - return ( - - {shortAddress(value)} - - ) - } - return ( - - {shortAddress(address)} - - ) - } - // Anything the cases above do not know. Shown rather than dropped: the index - // holds every field the runtime emitted, and a page that hides the ones it - // has no styling for is lying by omission. - return ( - - {typeof value === 'object' ? JSON.stringify(value) : String(value)} - - ) +function label(row: AccountEvent): string { + return LABELS[`${row.pallet}::${row.name}`] ?? `${row.pallet}::${row.name}` } export function AccountPanel({ @@ -267,7 +164,7 @@ export function AccountPanel({ Block - Event + What Detail @@ -278,25 +175,59 @@ export function AccountPanel({ - {detail.activity.map((event) => ( - + {detail.activity.map((row) => ( + - - #{fmtHeight(event.height)} + + #{fmtHeight(row.height)} - {label(event)} - + {label(row)} + {/* A request and a result read differently and must + not look the same: an extrinsic is what somebody + asked for, and unlike an event it can have + failed. */} + {row.source === 'extrinsic' && ( + + {row.signer === null + ? 'inherent' + : row.signer === detail.account + ? 'sent' + : 'received'} + + )} + {row.success === false && ( + + failed + + )} + + + + - {when(event.at)} + {when(row.at)} ))} @@ -310,7 +241,9 @@ export function AccountPanel({ has not made that claim yet — saying so is the difference between "nothing before block 8,075" and "nothing, as far as we looked". */}

- Read from the chain's own events, decoded against the runtime that produced each block. + Requests and results together: an extrinsic is what somebody asked the + chain to do, an event is what it then reported. Both decoded against the runtime that + produced each block. {detail.indexed_from !== null && detail.indexed_to !== null && ( <> {' '} diff --git a/web/src/components/BlockPanel.tsx b/web/src/components/BlockPanel.tsx index ad7f8da..d3348b0 100644 --- a/web/src/components/BlockPanel.tsx +++ b/web/src/components/BlockPanel.tsx @@ -21,8 +21,16 @@ import { Link } from 'react-router-dom' import type { BlockDetail } from '../api/generated/BlockDetail' import { RequestFailed, fetchBlock } from '../api/rest' -import { ago, bigNumber, height as fmtHeight, seconds, shortMiner } from '../lib/format' +import { + ago, + bigNumber, + height as fmtHeight, + seconds, + shortAddress, + shortMiner, +} from '../lib/format' import { href } from '../lib/routes' +import { Payload } from './Payload' /** A label and its value, with the caveat that makes the value readable. */ function Fact({ @@ -55,6 +63,8 @@ export function BlockPanel({ chain, block, targetSeconds, + decimals, + symbol, onResolved, }: { chain: string @@ -62,6 +72,10 @@ export function BlockPanel({ block: string /** The chain's target block time, for reading the gap against. */ targetSeconds: number + /** The chain's token decimals, for rendering call arguments. */ + decimals: number + /** Its symbol. */ + symbol: string /** Called with the canonical hash once a height has resolved to one. */ onResolved: (hash: string) => void }) { @@ -217,6 +231,99 @@ export function BlockPanel({ + {/* The body, decoded. The count in the facts above comes from the + node and goes when the node forgets the block; these come from + this observer's index and stay. An empty list is therefore not + "no extrinsics" — a block always has at least a timestamp — it is + "the index has not read this block yet", and it says so. */} +

+
+ Extrinsics{detail.body.length > 0 && ` (${detail.body.length})`} +
+ {detail.body.length === 0 ? ( +

+ {detail.extrinsics === null + ? 'Not indexed, and the node cannot answer for this block either.' + : `The node reports ${detail.extrinsics} in the body; the event index has not read this block yet. It works outward from the tip.`} +

+ ) : ( +
+ + + + + + + + + + + + + {detail.body.map((x) => ( + + + + + + + + ))} + +
+ This block's extrinsics, in body order +
# + Call + + Signer + + Arguments + Signature
{x.index} + + + {x.pallet}::{x.call} + + {x.success === false && ( + + failed + + )} + + + {x.signer_address ? ( + + {shortAddress(x.signer_address)} + + ) : ( + /* Not anonymous: nobody signed it. An inherent is + the block author's own, and the chain accepts it + because of where it sits, not because of a + signature. */ + inherent + )} + + + + {x.signature ? `${Math.round(x.signature_bytes / 1024)} KiB` : '—'} +
+
+ )} +
+
{detail.parent_hash && (
diff --git a/web/src/components/Payload.tsx b/web/src/components/Payload.tsx new file mode 100644 index 0000000..8c00c95 --- /dev/null +++ b/web/src/components/Payload.tsx @@ -0,0 +1,133 @@ +/** + * Rendering a decoded call's arguments or an event's fields. + * + * One component for both because they are the same thing: a JSON object whose + * keys are names the runtime chose, whose account ids are `0x` hex, and whose + * integers past 2^53 are strings. Neither the block page nor the account page + * knows what a transfer is, and neither should — a pallet added next year + * renders here without a line of code. + * + * `AMOUNTS` is presentation only. A field it does not recognise still appears, + * as its key and its value; the list decides which of them get the token + * treatment rather than which of them exist. That is the difference between a + * page that shows what happened and one that shows the subset somebody + * remembered to write a case for. + */ + +import { Link } from 'react-router-dom' + +import { exactTokens, shortAddress, tokens } from '../lib/format' +import { href } from '../lib/routes' + +/** Field names that carry a balance, and so want the token treatment. */ +const AMOUNTS = new Set(['reward', 'amount', 'value', 'fee', 'actual_fee', 'tip']) + +/** A 32-byte account id, which is what the decoder renders accounts as. */ +function isAccount(value: unknown): value is string { + return typeof value === 'string' && /^0x[0-9a-f]{64}$/.test(value) +} + +export interface PayloadContext { + chain: string + /** `0x hex → SS58` for every account the payload mentions. */ + addresses: Record + decimals: number + symbol: string + /** Folded out of the rendering: the account whose page this is. Every row + * involves it by definition, and repeating it buries the half that differs. */ + focus?: string +} + +export function Payload({ value, ctx }: { value: unknown; ctx: PayloadContext }) { + const shown = Object.entries((value ?? {}) as Record).filter( + ([, v]) => !(ctx.focus && isAccount(v) && v === ctx.focus), + ) + if (shown.length === 0) return — + return ( + + {shown.map(([key, v]) => ( + + {/* The key only when there is something to tell apart. A reward has + one field left once the page's own account is folded out, and + "REWARD 0.31 QTC" in a column headed Detail says it twice. */} + {shown.length > 1 && {key}} + + + ))} + + ) +} + +function Value({ name, value, ctx }: { name: string; value: unknown; ctx: PayloadContext }) { + if (AMOUNTS.has(name) && (typeof value === 'string' || typeof value === 'number')) { + const raw = String(value) + return ( + + {tokens(raw, ctx.decimals)} {ctx.symbol} + + ) + } + + if (isAccount(value)) { + // The counterparty in the spelling they would recognise, and as a way to + // their own page. The raw id stays in the title, because it is what the + // chain stored and what anyone checking our working needs. + const address = ctx.addresses[value] + if (!address) { + return ( + + {shortAddress(value)} + + ) + } + return ( + + {shortAddress(address)} + + ) + } + + // A nested structure: a `MultiAddress::Id` wrapper, or a whole call inside a + // `Utility::batch_all`. Recursing rather than stringifying is what lets a + // batched transfer show its recipient instead of a wall of JSON. + if (value && typeof value === 'object') { + const entries = Object.entries(value as Record) + // A single-key object is a variant wrapper — `{Id: "0x…"}`, + // `{Balances: {…}}` — and its key is the name, not a field. + if (entries.length === 1) { + const [only, inner] = entries[0]! + if (isAccount(inner) || typeof inner !== 'object') { + return + } + return ( + + {only} + + + ) + } + if (Array.isArray(value)) { + return ( + + {value.map((item, i) => ( + + ))} + + ) + } + return ( + + + + ) + } + + // Anything the cases above do not know. Shown rather than dropped: the index + // holds every field the runtime emitted, and a page that hides the ones it + // has no styling for is lying by omission. + return {String(value)} +} diff --git a/web/src/index.css b/web/src/index.css index 9b2769e..429862a 100644 --- a/web/src/index.css +++ b/web/src/index.css @@ -1248,3 +1248,29 @@ tr.mine .share-bar > i { font-size: 11px; color: var(--text-muted); } + +/* A nested value inside a call's arguments — a `MultiAddress::Id` wrapper, or a + whole call inside a `Utility::batch_all`. Indented rather than bracketed: + the nesting is the structure the runtime describes, and flattening it would + lose which recipient belongs to which transfer. */ +.event-nested { + display: inline-flex; + flex-wrap: wrap; + align-items: baseline; + gap: 4px 8px; +} + +/* Where a history row came from, and whether it worked. `chip-submitted` is + deliberately quiet — it is a category, not a warning — and `chip-failed` + borrows the accent because it is the one thing on the row that changes what + the row means. */ +.chip-submitted { + color: var(--text-muted); + border-color: var(--border); +} + +.chip-failed { + color: var(--accent-bright); + border-color: var(--accent); + background: rgba(216, 69, 58, 0.12); +}